如何在Kotlin中创建匿名接口的实例? [英] How to create an instance of anonymous interface in Kotlin?
本文介绍了如何在Kotlin中创建匿名接口的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有第三方Java库,其对象具有如下界面:
I have a third party Java library which an object with interface like this:
public interface Handler<C> {
void call(C context) throws Exception;
}
如何在Kotlin中简洁地实现它,类似于Java匿名类,如下所示:
How can I concisely implement it in Kotlin similar to Java anonymous class like this:
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"
推荐答案
假设界面只有一种方法,你可以使用 SAM
Assuming the interface has only a single method you can make use of 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") }
}
这篇关于如何在Kotlin中创建匿名接口的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文