那段代码在 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) {
//...
}
}
如果你正在将接口和其实现都重写为Kotlin,那么你应该删除接口并使用函数类型:
val impl: (MyClass, Int) -> Unit = { inst, num -> ... }
val listener: (name: Class, other: OtherClass) -> Unit
- TheWanderer(String) -> String
做什么?没有名称,你无法理解它。现在,这个签名的函数 (UserId) -> PhoneNumber
做什么?嗯,唯一合理的实现方式是通过ID查找用户数据,然后提取电话号码并返回它。如果你的函数不使用原始类型,则通常不需要将它们包装在接口中以提高可读性。 - Matt Klein您可以使用对象表达式。
这样看起来就像这样:
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 ->
//..
}