Inheritance 如何让数据类在Kotlin中实现接口/扩展超类属性?

Inheritance 如何让数据类在Kotlin中实现接口/扩展超类属性?,inheritance,properties,kotlin,data-class,Inheritance,Properties,Kotlin,Data Class,我有几个数据类,其中包括一个varid:Int?字段。我想在接口或超类中表达这一点,并让数据类扩展它,并在构建时设置这个id。但是,如果我尝试这样做: interface B { var id: Int? } data class A(var id: Int) : B(id) 它抱怨我正在覆盖id字段,我是哈哈 Q:在这种情况下,我如何让数据类A在构造时获取id,并设置接口或超类中声明的id?确实,您还不需要。您可以只覆盖属性,例如: interface B { val id:

我有几个数据类,其中包括一个
varid:Int?
字段。我想在接口或超类中表达这一点,并让数据类扩展它,并在构建时设置这个
id
。但是,如果我尝试这样做:

interface B {
  var id: Int?
}

data class A(var id: Int) : B(id)
它抱怨我正在覆盖
id
字段,我是哈哈

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

确实,您还不需要。您可以只覆盖属性,例如:

interface B {
    val id: Int?
}

//           v--- override the interface property by `override` keyword
data class A(override var id: Int) : B
//               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)
An没有构造函数,因此不能通过
super(…)
关键字调用构造函数,但可以使用。但是,a不能在其上声明任何参数,因此它将覆盖超类的字段,例如:

interface B {
    val id: Int?
}

//           v--- override the interface property by `override` keyword
data class A(override var id: Int) : B
//               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)

谢谢你,这就是我需要知道的。@EdyBourne一点也不想知道。事实上,我被问题中的超类词弄糊涂了,第一次滥用了抽象类。我意识到让
数据类
扩展
会有一些麻烦,直到我写下答案。所以我改变了主意,最终发现您只想实现接口getter/setters。
openval
-对吗?看起来像是受保护的最终版@Abhijit Sarkar嗨,没问题。因为它声明它的getter可以被重写,它的back字段也是final。@Abhijit Sarkar是的,但是visibilitybis not changed getter是公共的。