[英]Can I extend, in Java, a Kotlin delegating class?
I'm trying to extend, in Java, a Kotlin delegating class and get the following error: 我试图在Java中扩展一个Kotlin委托类并得到以下错误:
Cannot inherit from final 'Derived'
无法继承最终'衍生'
See code below. 见下面的代码。
What I'm trying to do is decorate a method of a class. 我要做的是装饰一个类的方法。
Any idea why Kotlin defined Derived
as final? 知道为什么Kotlin定义
Derived
为final? Is there a way for Derived
to not be final so I can inherit it? 有没有一种方法让
Derived
不是最终的,所以我可以继承它?
Java: Java的:
new Derived(new BaseImpl(10)) { // Getting the error on this line: `Cannot inherit from final 'Derived'`
};
Kotlin: 科特林:
interface Base {
fun print()
}
class BaseImpl(val x: Int) : Base {
override fun print() { print(x) }
}
class Derived(b: Base) : Base by b
* Example from here: https://kotlinlang.org/docs/reference/delegation.html *此处的示例: https : //kotlinlang.org/docs/reference/delegation.html
Kotlin classes are final in by default . Kotlin类默认为最终版 。 Mark the class as
open
to extend it (whether from Kotlin or from Java): 将该类标记为
open
以扩展它(无论是来自Kotlin还是来自Java):
open class Derived(b: Base) : Base by b
The fact this is a delegating class should have no impact on Java interop (although I haven't tried it). 事实上,这是一个委托类应该对Java互操作没有影响(虽然我还没有尝试过)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.