Java 如何在 Kotlin 中创建匿名接口的实例?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37672023/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create an instance of anonymous interface in Kotlin?
提问by Peter Lamberg
I have a third party Java library which an object with interface like this:
我有一个第三方 Java 库,它有一个像这样接口的对象:
public interface Handler<C> {
void call(C context) throws Exception;
}
How can I concisely implement it in Kotlin similar to Java anonymous class like this:
我如何在 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"
采纳答案by miensol
Assuming the interface has only a single method you can make use of SAM
假设接口只有一个方法,您可以使用SAM
val handler = Handler<String> { println("Hello: $it")}
If you have a method that accepts a handler then you can even omit type arguments:
如果您有一个接受处理程序的方法,那么您甚至可以省略类型参数:
fun acceptHandler(handler:Handler<String>){}
acceptHandler(Handler { println("Hello: $it")})
acceptHandler({ println("Hello: $it")})
acceptHandler { println("Hello: $it")}
If the interface has more than one method the syntax is a bit more verbose:
如果接口有多个方法,则语法会更冗长:
val handler = object: Handler2<String> {
override fun call(context: String?) { println("Call: $context") }
override fun run(context: String?) { println("Run: $context") }
}
回答by Peter Lamberg
The simplest answer probably is the Kotlin's lambda:
最简单的答案可能是 Kotlin 的 lambda:
val handler = Handler<MyContext> {
println("Hello world")
}
handler.call(myContext) // Prints "Hello world"
回答by Aalap
I had a case where I did not want to create a var for it but do it inline. The way I achieved it is
我有一个案例,我不想为它创建一个 var 而是内联。我实现它的方式是
funA(object: InterfaceListener {
override fun OnMethod1() {}
override fun OnMethod2() {}
override fun OnPermissionsDeniedForever() {}
})
回答by pruthwiraj.kadam
val obj = object : MyInterface {
override fun function1(arg:Int) { ... }
override fun function12(arg:Int,arg:Int) { ... }
}