Can I extend the Kotlin delegation class to Java?

I am trying to extend the Kotlin delegation class in Java and get the following error:

Unable to inherit from final 'Derived'

See the code below.

What I'm trying to do is decorate a class method.

Any idea why Kotlin identified Derived as final? Is there a way for Derived not to be final so that 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

+5
source share
1 answer

By default, Kotlin classes are final . Mark the class as open to extend it (from Kotlin or from Java):

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

The fact that this is a delegating class should not affect Java interaction (although I have not tried it).

+9
source

Source: https://habr.com/ru/post/1269941/


All Articles