我有一个第三方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:

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"

推荐答案

Assuming the interface has only a single method you can make use of SAM.

val handler = Handler<String> { println("Hello: $it") }

Since version 1.4 Kotlin supports SAM for interfaces defined in Kotlin. That requires prefixing the interface keyword with fun

fun interface Handler<C> {
  fun call(context: C);
}

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相关问答推荐

Groovy Gradle文件的Kotlin类似功能

在Kotlin中,我是否可以访问已知的WHEN子句值?

用vararg替换列表的设计弃用警告

Kotlin 说不需要强制转换,但删除后会出现新警告

try 一次性插入多条记录时,JOOQ连接为空错误

kotlin 模式匹配如何像 scala 一样工作

Kotlin - 如何避免在密封类的 when() 语句中转换第二个变量

Kotlin 协程按顺序执行,但仅在生产机器上执行

Kotlin 中的密封和内部有什么区别?

如何在 jOOQ 中两次加入同一张表?

Kotlin SAM/功能接口抛出 AbstractMethodError

Jetpack Compose - 单击 LazyColumn 的项目时应用程序崩溃

如何在 Hibernate Panache 中进行部分搜索

Jetpack BottomNavigation - java.lang.IllegalStateException:Already attached to lifecycleOwner

AIDL 中的 Parcelize 注释:Incompatible types: Object cannot be converted to MyCustomObject

runBlocking 中的 deferred.await() 抛出的异常即使在被捕获后也被视为未处理

如何解决此错误请Kotlin:[Internal Error] java.lang.ExceptionInInitializerError

将多个 Kotlin 流合并到一个列表中,而无需等待第一个值

将字符串编码为Kotlin中的UTF-8

如何在 IntelliJ IDEA 中禁用粘贴时将 Java 转换为 Kotlin?