如何让一个数据类在Kotlin中实现Interface / extends Superclass属性?

我有几个数据类,其中包括一个var id: Int? 领域。 我想在接口超类中表达这个,并且有数据类扩展,并在构造时设置这个id 。 但是,如果我尝试这样做:

 interface B { var id: Int? } data class A(var id: Int) : B(id) 

它抱怨我重写id字段,我哈哈..

:在这种情况下,如何让数据类A在构造时使用一个id ,并将接口超类中声明的id设置为?

的确,你还不需要抽象类 。 您可以覆盖接口属性,例如:

 interface B { val id: Int? } // v--- override the interface property by `override` keyword data class A(override var id: Int) : B 

一个接口没有构造函数,所以你不能通过super(..)关键字来调用构造函数,但是你可以使用一个抽象类来代替。 Howerver, 数据类不能在其主构造函数中声明任何参数,所以它将覆盖超类的字段 ,例如:

 // v--- makes it can be override with `open` keyword abstract class B(open val id: Int?) // v--- override the super property by `override` keyword data class A(override var id: Int) : B(id) // ^ // the field `id` in the class B is never used by A // pass the parameter `id` to the super constructor // v class NormalClass(id: Int): B(id)