Lambda在kotlin中实现接口 [英] Lambda implementation of interface in kotlin
本文介绍了Lambda在kotlin中实现接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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);
}
init:
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)
}
...你可以使用对象
匿名实现它的语法:
...you can use the object
syntax for implementing it anonymously:
val impl = object : AnInterface {
override fun doSmth(inst:, num: Int) {
//...
}
}
这篇关于Lambda在kotlin中实现接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文