简体   繁体   中英

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:

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? Is there a way for Derived to not be final so I can inherit it?

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

Kotlin classes are final in by default . Mark the class as open to extend it (whether from Kotlin or from 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM