我试图继承以下类型,但编译器说它是最终的. 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 n
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
为什么我的类型是最终的,因为我不打算这样做?
在Kotlin中,与Java和C#不同,默认情况下所有类都是final,除非明确标记为open.这是 the docs的内容:The
open
annotation on a class is the opposite of Java’sfinal
: it allows others to inherit from this class. By default, all classes in Kotlin are final, which corresponds to 07001, Item 17: Design and document for inheritance or else prohibit it.
解决方案只是将您的类标记为开放类Dice.
另外,请注意limitations on data
classes继承:它们既不能打开也不能扩展另一个类.