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") }
// 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) { ... }
1 回答
根据Kotlin关于Java interop的文档,对于Java中定义的功能接口,您可以使用SAM转换 .
但是,Kotlin具有功能类型,因此SAM转换不适用于Kotlin中定义的接口:
可能的解决方案:
用Java定义接口 . 如果它是可以从Java代码使用的库/代码,则很有用 .
使方法接收函数作为参数: