Kotlin use Java callback interface

别等时光非礼了梦想. 提交于 2020-02-27 23:15:05

问题


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!


回答1:


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
}



回答2:


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


来源:https://stackoverflow.com/questions/44208164/kotlin-use-java-callback-interface

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!