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

Edy*_*rne 6 inheritance properties kotlin data-class

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

interface B {
  var id: Int?
}

data class A(var id: Int) : B(id)
Run Code Online (Sandbox Code Playgroud)

它抱怨我压倒了这个id领域,我是哈哈.

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

hol*_*ava 7

实际上,你还不需要抽象课程.你可以覆盖界面属性,例如:

interface B {
    val id: Int?
}

//           v--- override the interface property by `override` keyword
data class A(override var id: Int) : B
Run Code Online (Sandbox Code Playgroud)

一个接口有没有构造,所以你不能调用由构造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)
Run Code Online (Sandbox Code Playgroud)

  • @Abhijit Sarkar是的,但是能见度不变的吸气剂是公开的. (2认同)