【问题标题】:Java vs Kotlin interface declaration [duplicate]Java vs Kotlin接口声明[重复]
【发布时间】:2017-07-09 23:52:10
【问题描述】:

假设我有这个 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 的实例?

【问题讨论】:

标签: java interface kotlin


【解决方案1】:

这是因为 Kotlin 的 SAM(“单一抽象方法”)仅适用于 Java 接口。 design 就是这样。 docs 上也有一些相关信息:

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

Related issue

【讨论】:

  • 我接受它不受支持的事实。但我不明白为什么 Kotlin 不需要这样的功能?这是一种创建 SAM 接口实例的便捷方式。
  • @HendraAnggrian Andrey Breslav(kotlin 项目负责人)说:SAM 转换仅适用于 Java 方法,不支持 Kotlin 函数,因为 Kotlin 有很好的函数类型,并且不需要 SAM 转换跨度>
  • 查看此链接了解更多信息discuss.kotlinlang.org/t/…
  • 我想我现在可能知道为什么了。接口很容易被 Kotlin 中的 Unit 替换。感谢您提供有用的链接!
猜你喜欢
  • 1970-01-01
  • 2019-04-24
  • 2012-10-24
  • 2018-07-10
  • 2018-05-30
  • 2011-04-24
  • 2011-07-08
  • 2018-01-12
  • 2011-05-01
相关资源
最近更新 更多