Java与Kotlin接口声明

说我有这个Java和Kotlin接口:

public interface JavaInterface { void onTest(); } interface KotlinInterface { fun onTest() } 

为什么不能在没有构造函数的情况下创建Kotlin接口的实例?

 // this is okay val javaInterface: JavaInterface = JavaInterface { } // compile-time exception: interface does not have constructor val kotlinInterface1: KotlinInterface = KotlinInterface { } // this is okay val kotlinInterface2: KotlinInterface = object : KotlinInterface { override fun onTest() { } } 

为什么不能像我第一个例子那样用KotlinInterface创建一个KotlinInterface的实例?

这是因为Kotlin仅有Java接口的SAM(“单一抽象方法”)。 这是通过设计的方式。 关于这个文档也有一些信息:

另请注意,此功能仅适用于Java interop; 由于Kotlin具有适当的函数类型,函数自动转换为Kotlin接口的实现是不必要的,因此不受支持。

相关问题