我可以在 Java 中扩展 Kotlin 委托 class 吗?
Can I extend, in Java, a Kotlin delegating class?
我正在尝试在 Java 中扩展 Kotlin 委托 class 并收到以下错误:
Cannot inherit from final 'Derived'
请参阅下面的代码。
我想做的是装饰一个 class.
的方法
知道为什么 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
Kotlin classes are final in by default。将 class 标记为 open
以扩展它(无论是来自 Kotlin 还是来自 Java):
open class Derived(b: Base) : Base by b
事实上这是一个委派 class 应该不会对 Java 互操作产生影响(尽管我还没有尝试过)。
我正在尝试在 Java 中扩展 Kotlin 委托 class 并收到以下错误:
Cannot inherit from final 'Derived'
请参阅下面的代码。
我想做的是装饰一个 class.
的方法知道为什么 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
Kotlin classes are final in by default。将 class 标记为 open
以扩展它(无论是来自 Kotlin 还是来自 Java):
open class Derived(b: Base) : Base by b
事实上这是一个委派 class 应该不会对 Java 互操作产生影响(尽管我还没有尝试过)。