3

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?

Ilya
  • 21,871
  • 8
  • 73
  • 92
barakisbrown
  • 1,293
  • 3
  • 9
  • 15

1 Answers1

7

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.

Community
  • 1
  • 1
hotkey
  • 140,743
  • 39
  • 371
  • 326