Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 438
AlikElzin-kilaka Avatar asked Jul 18 '17 11:07

AlikElzin-kilaka


People also ask

Can a Java class extend a Kotlin class?

A class can implement as many interfaces as you want, but it can only extend a single class (similar to Java). The override modifier is compulsory in Kotlin—unlike in Java. Along with methods, we can also declare properties in a Kotlin interface.

Which class Cannot extend?

You cannot extend a final class.

Can you extend classes in Java?

The extends keyword extends a class (indicates that a class is inherited from another class). In Java, it is possible to inherit attributes and methods from one class to another.

Can you extend a class that extends another class?

You can extend a class to provide more specialized behavior. A class that extends another class inherits all the methods and properties of the extended class. In addition, the extending class can override the existing virtual methods by using the override keyword in the method definition.


1 Answers

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).

like image 152
Oliver Charlesworth Avatar answered Sep 30 '22 02:09

Oliver Charlesworth