【问题标题】:Can I extend, in Java, a Kotlin delegating class?我可以在 Java 中扩展 Kotlin 委托类吗?
【发布时间】:2017-12-23 06:30:25
【问题描述】:

我正在尝试在 Java 中扩展 Kotlin 委托类并得到以下错误:

不能从最终的“派生”继承

参见下面的代码。

我想做的是装饰一个类的方法。

知道为什么 Kotlin 将 Derived 定义为 final 吗?有没有办法让Derived 不是最终的,所以我可以继承它?

Java:

new Derived(new BaseImpl(10)) { // Getting the error on this line: `Cannot inherit from final 'Derived'`
};

科特林:

interface Base {
    fun print()
}

class BaseImpl(val x: Int) : Base {
    override fun print() { print(x) }
}

class Derived(b: Base) : Base by b

* 此处的示例:https://kotlinlang.org/docs/reference/delegation.html

【问题讨论】:

    标签: java kotlin decorator delegation


    【解决方案1】:

    Kotlin classes are final in by default。将类标记为 open 以扩展它(无论是来自 Kotlin 还是来自 Java):

    open class Derived(b: Base) : Base by b
    

    事实上这是一个委托类应该对 Java 互操作没有影响(尽管我没有尝试过)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-09-03
      • 2018-12-14
      • 1970-01-01
      • 1970-01-01
      • 2016-02-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多