7

I have a WebView. I want to call

public void evaluateJavascript(String script, ValueCallback<String> resultCallback)

this method.

Here is the ValueCallback interface:

public interface ValueCallback<T> {
    /**
     * Invoked when the value is available.
     * @param value The value.
     */
    public void onReceiveValue(T value);
};

Here is my kotlin code:

webView.evaluateJavascript("a", ValueCallback<String> {
            // cant override function
        })

Anyone have idea to override the onReceiveValue method in kotlin? I tried the "Convert Java to Kotlin" but result is the next:

v.evaluateJavascript("e") {  }

Thanks!

Jayson Minard
  • 84,842
  • 38
  • 184
  • 227
vihkat
  • 895
  • 3
  • 13
  • 28

2 Answers2

12

The following line is called a SAM conversion:

v.evaluateJavascript("e", { value ->
  // Execute onReceiveValue's code
})

Whenever a Java interface has a single method, Kotlin allows you to pass in a lambda instead of an object that implements that interface.

Since the lambda is the last parameter of the evaluateJavascript function, you can move it outside of the brackets, which is what the Java to Kotlin conversion did:

v.evaluateJavascript("e") { value ->
  // Execute onReceiveValue's code
}
nhaarman
  • 98,571
  • 55
  • 246
  • 278
7

You already are. The content between your braces is the content of the onReceive function. Kotlin has automatic handling for SAM conversions from Java. All of the following are equivalent.

// Use Kotlin's SAM conversion
webView.evaluateJavascript("a") {
    println(it)  // "it" is the implicit argument passed in to this function
}

// Use Kotlin's SAM conversion with explicit variable name
webView.evaluateJavascript("a") { value ->
    println(value)
}

// Specify SAM conversion explicitly
webView.evalueateJavascript("a", ValueCallback<String>() {
    println(it)
})

// Use an anonymous class
webView.evalueateJavascript("a", object : ValueCallback<String>() {
    override fun onReceiveValue(value: String) {
        println(value)
    }
})
Ruckus T-Boom
  • 4,566
  • 1
  • 28
  • 42
  • Are you sure about those close bracket `)` positions in first two? – weston May 26 '17 at 18:46
  • 3
    Yes, it's a feature of Kotlin. From the docs: "In Kotlin, there is a convention that if the last parameter to a function is a function, and you're passing a lambda expression as the corresponding argument, you can specify it outside of parentheses:" https://kotlinlang.org/docs/reference/lambdas.html – Ruckus T-Boom May 26 '17 at 18:47
  • 1
    That's nice. Great thorough answer. – weston May 26 '17 at 18:52