Pet*_*erg 68 java lambda anonymous kotlin
我有一个第三方Java库,其对象具有如下界面:
public interface Handler<C> {
void call(C context) throws Exception;
}
Run Code Online (Sandbox Code Playgroud)
我怎样才能在Kotlin中简洁地实现它,就像这样的Java匿名类:
Handler<MyContext> handler = new Handler<MyContext> {
@Override
public void call(MyContext context) throws Exception {
System.out.println("Hello world");
}
}
handler.call(myContext) // Prints "Hello world"
Run Code Online (Sandbox Code Playgroud)
mie*_*sol 104
假设界面只有一种方法,您可以使用SAM
val handler = Handler<String> { println("Hello: $it")}
Run Code Online (Sandbox Code Playgroud)
如果您有一个接受处理程序的方法,那么您甚至可以省略类型参数:
fun acceptHandler(handler:Handler<String>){}
acceptHandler(Handler { println("Hello: $it")})
acceptHandler({ println("Hello: $it")})
acceptHandler { println("Hello: $it")}
Run Code Online (Sandbox Code Playgroud)
如果接口有多个方法,则语法有点冗长:
val handler = object: Handler2<String> {
override fun call(context: String?) { println("Call: $context") }
override fun run(context: String?) { println("Run: $context") }
}
Run Code Online (Sandbox Code Playgroud)
我有一种情况,我不想为其创建var,而是内联。我实现它的方式是
funA(object: InterfaceListener {
override fun OnMethod1() {}
override fun OnMethod2() {}
override fun OnPermissionsDeniedForever() {}
})
Run Code Online (Sandbox Code Playgroud)
val obj = object : MyInterface {
override fun function1(arg:Int) { ... }
override fun function12(arg:Int,arg:Int) { ... }
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
27891 次 |
| 最近记录: |