Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this class considered final?

I am trying to inherit the following type, but the compiler says it is final.

class Dice(private var side : Int)
{
    constructor(D : DiceTypesK) : this(D.value) {}
}

class ExplodedDice(private val D : DiceTypesK) : Dice(D) 
                                              // ^^^^ this class is final and
                                              //      can not be inherited from

Why my type is final, because I did not intend it to be?

like image 250
barakisbrown Avatar asked Jul 06 '26 19:07

barakisbrown


1 Answers

In Kotlin, unlike Java and C#, all classes are final by default, unless marked as open explicitly. Here's what's in the docs:

The open annotation on a class is the opposite of Java’s final: it allows others to inherit from this class. By default, all classes in Kotlin are final, which corresponds to Effective Java, Item 17: Design and document for inheritance or else prohibit it.

The solution is just to mark your class as open class Dice.

Also, note the limitations on data classes inheritance: they can neither be open nor extend another class.

like image 95
hotkey Avatar answered Jul 08 '26 08:07

hotkey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!