Lambda在kotlin中的接口实现
kotlin中的代码会是什么样子,似乎没有什么工作我尝试:
public interface AnInterface { void doSmth(MyClass inst, int num); }
在里面:
AnInterface impl = (inst, num) -> { //... }
如果AnInterface
是Java,则可以使用SAM转换 :
val impl = AnInterface { inst, num -> //... }
否则,如果界面是Kotlin …
interface AnInterface { fun doSmth(inst: MyClass, num: Int) }
…您可以使用object
语法来匿名实现它:
val impl = object : AnInterface { override fun doSmth(inst:, num: Int) { //... } }
你可以使用一个对象expression式
所以它看起来像这样:
val impl = object : AnInterface { override fun(doSmth: Any, num: Int) { TODO() } }
如果您将接口及其实现重写为Kotlin,那么您应该删除接口并使用functiontypes:
val impl: (MyClass, Int) -> Unit = { inst, num -> ... }