Kotlin uses Java callback interface

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 }) 

Does anyone have an idea to override the onReceiveValue method in kotlin? I tried Convert Java to Kotlin, but the result is as follows:

 v.evaluateJavascript("e") { } 

Thanks!

+5
source share
2 answers

The next line is called a SAM conversion :

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

Whenever the Java interface has one method, Kotlin allows you to pass to lambda instead of an object that implements this interface.

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

 v.evaluateJavascript("e") { value -> // Execute onReceiveValue code } 
+6
source

You are already there. The content between your curly braces is the content of the onReceive function. Kotlin has automated SAM conversion processing with Java. All of the following equivalents.

 // Use Kotlin SAM conversion webView.evaluateJavascript("a") { println(it) // "it" is the implicit argument passed in to this function } // Use Kotlin 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) } }) 
+4
source

Source: https://habr.com/ru/post/1268267/


All Articles