Kotlin使用Java回调接口

Kotlin使用Java回调接口

本文介绍了Kotlin使用Java回调接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个WebView.我想打电话

I have a WebView. I want to call

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

此方法.

这是ValueCallback接口:

Here is the ValueCallback interface:

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

这是我的kotlin代码:

Here is my kotlin code:

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

有人想重写kotlin中的onReceiveValue方法吗?我尝试了将Java转换为Kotlin",但结果是下一个:

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

谢谢!

推荐答案

以下行称为 SAM转换:

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

只要Java接口具有单个方法,Kotlin都允许您传递lambda而不是实现该接口的对象.

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

由于lambda是evaluateJavascript函数的最后一个参数,因此您可以将其移到方括号之外,这就是Java到Kotlin的转换:

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
}

这篇关于Kotlin使用Java回调接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 07:03