微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

android – kotlin如何使setOnClickListener接受函数作为参数

在kotlin中,我们可以像这样使用setonClickListener():

view.setonClickListener { println("Hello") }

但是如果我定义自己的界面,我只能传递这样的匿名对象:

obj.setMyListener(object: MyListener() {
    ...
})

我只是想知道他们如何使setonClickListener()接受一个函数而不是一个匿名对象.

解决方法:

根据Kotlin关于Java interop的文档,对于Java中定义的功能接口,您可以使用SAM转换.

Just like Java 8, Kotlin supports SAM conversions. This means that
Kotlin function literals can be automatically converted into
implementations of Java interfaces with a single non-default method,
as long as the parameter types of the interface method match the
parameter types of the Kotlin function.

val runnable = Runnable { println("This runs in a runnable") }

val executor = ThreadPoolExecutor()
// Java signature: void execute(Runnable command)
executor.execute { println("This runs in a thread pool") }

但是,Kotlin具有功能类型,因此SAM转换不适用于Kotlin中定义的接口:

Also note that this feature works only for Java interop; since Kotlin
has proper function types, automatic conversion of functions into
implementations of Kotlin interfaces is unnecessary and therefore
unsupported.

可能的解决方案:

>使用Java定义接口.如果它是可以从Java代码使用的库/代码,则很有用.
>使方法接收函数作为参数:

// Example listener receives a bool and return unit.  
fun setMyListener(listener: (isChecked: Bool) -> Unit) { ... }  
// Usage:  
obj.setMyListener { isChecked -> }

>使用类型别名(仅在Kotlin 1.1中支持):

typealias MyListener = (Bool) -> Unit
fun setMyListener(listener: MyListener) { ... }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐