Java与Kotlin接口声明

Java与Kotlin接口声明,java,interface,kotlin,Java,Interface,Kotlin,假设我有Java和Kotlin接口: public interface JavaInterface { void onTest(); } interface KotlinInterface { fun onTest() } 为什么我不能在没有构造函数的情况下创建Kotlin接口的实例 // this is okay val javaInterface: JavaInterface = JavaInterface { } // compile-time exceptio

假设我有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
的实例,就像我在
JavaExample
中所做的那样?

这是因为Kotlin只有针对Java接口的SAM(“单一抽象方法”)。这边走。网上也有一些关于这方面的信息:

还请注意,此功能仅适用于Java互操作;由于Kotlin具有适当的函数类型,因此不需要将函数自动转换为Kotlin接口的实现,因此不受支持


我认为这是这个问题的一个变体:@OliverCharlesworth是的,先生,看起来是这样。我接受这个事实,即它不受支持。但我不明白为什么Kotlin中不需要这样的功能?创建SAM接口实例非常方便。@HendraAnggrian Andrey Breslav(kotlin项目负责人)说:SAM转换只适用于Java方法,kotlin函数不支持,因为kotlin有很好的函数类型,没有必要进行SAM转换查看此链接了解更多信息我想我现在可能已经知道原因了。接口很容易被Kotlin中的单元替换。谢谢你的帮助链接!