在kotlin中实现接口的Lambda

Joc*_*Doe 23 java methods lambda interface kotlin

什么是相当于kotlin中的代码,似乎没有什么工作我尝试:

public interface AnInterface {
    void doSmth(MyClass inst, int num);
}
Run Code Online (Sandbox Code Playgroud)

在里面:

AnInterface impl = (inst, num) -> {
    //...
}
Run Code Online (Sandbox Code Playgroud)

s1m*_*nw1 20

如果AnInterface是Java,您可以使用SAM转换:

val impl = AnInterface { inst, num -> 
     //...
}
Run Code Online (Sandbox Code Playgroud)

否则,如果界面是Kotlin ......

interface AnInterface {
     fun doSmth(inst: MyClass, num: Int)
}
Run Code Online (Sandbox Code Playgroud)

...您可以使用object语法匿名实现它:

val impl = object : AnInterface {
    override fun doSmth(inst:, num: Int) {
        //...
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 为什么 Kotlin 接口没有与 Java 类似的 SAM 转换?这个 AnInterface { inst, num -> } 有什么办法也适用于 Kotlin 接口吗? (2认同)

Mar*_*nik 15

如果您正在将接口及其实现重写为Kotlin,那么您应该删除接口并使用功能类型:

val impl: (MyClass, Int) -> Unit = { inst, num -> ... }
Run Code Online (Sandbox Code Playgroud)

  • @SiraLam如果您希望界面出于可读性的原因,那么您可能会遇到Primitive Obsession.tl; dr - 不要使用基元作为参数.这个签名的功能有什么作用?`(String) - > String`没有名字,你无法推理它.现在,这个签名的功能是做什么的?`(UserId) - > PhoneNumber` - 嗯,唯一合理的实现是通过ID查找用户数据,然后拉出电话号码并返回它.如果您的函数不采用原语,那么通常不需要将它们包装在接口中以提高可读性. (2认同)