Search code examples
kotlinkotlin-interop

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

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!


Solution

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