Kotlin 中的代码相当于什么,我尝试的似乎没有任何效果:
public interface AnInterface {
void doSmth(MyClass inst, int num);
}
初始化:
AnInterface impl = (inst, num) -> {
//...
}
如果
AnInterface
是Java,则可以使用SAM转换:
val impl = AnInterface { inst, num ->
//...
}
否则,如果接口是 Kotlin:
从 Kotlin 1.4 开始,可以编写 函数式接口 :
fun interface AnInterface {
fun doSmth(inst: MyClass, num: Int)
}
val impl = AnInterface { inst, num -> ... }
否则,如果界面无法正常工作
interface AnInterface {
fun doSmth(inst: MyClass, num: Int)
}
您可以使用
object
语法来匿名实现它:
val impl = object : AnInterface {
override fun doSmth(inst:, num: Int) {
//...
}
}
如果您要将接口及其实现都重写为 Kotlin,那么您应该删除接口并使用函数类型:
val impl: (MyClass, Int) -> Unit = { inst, num -> ... }
您可以使用对象表达式
所以它看起来像这样:
val impl = object : AnInterface {
override fun(doSmth: Any, num: Int) {
TODO()
}
}
对于 2022 年阅读本文的任何人来说,Kotlin 现在有了函数式 (SAM) 接口。请参阅https://kotlinlang.org/docs/fun-interfaces.html
也许它会节省其他人一些时间,具体取决于您的用例。
您也可以使用
@lambda
标签 执行类似操作
interface AnInterface {
fun doSmth(inst: MyClass, num: Int)
}
val impl = AnInterface lambda@{inst, num ->
//..
}