kotlin中接口的Lambda实现 [英] Lambda implementation of interface in kotlin
本文介绍了kotlin中接口的Lambda实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
kotlin 中的代码的等价物是什么,我尝试的似乎没有任何效果:
What would be the equivalent of that code in kotlin, nothing seems to work of what I try:
public interface AnInterface {
void doSmth(MyClass inst, int num);
}
初始化:
AnInterface impl = (inst, num) -> {
//...
}
推荐答案
如果 AnInterface
是 Java,您可以使用 SAM 转换:
If AnInterface
is Java, you can work with SAM conversion:
val impl = AnInterface { inst, num ->
//...
}
否则,如果接口是 Kotlin...
Otherwise, if the interface is Kotlin...
interface AnInterface {
fun doSmth(inst: MyClass, num: Int)
}
...你可以使用 object
语法来匿名实现它:
...you can use the object
syntax for implementing it anonymously:
val impl = object : AnInterface {
override fun doSmth(inst:, num: Int) {
//...
}
}
这篇关于kotlin中接口的Lambda实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文