如何让数据 class 在 Kotlin 中实现接口/扩展 Superclass 属性?
How to let a data class implements Interface / extends Superclass properties in Kotlin?
我有几个数据 classes,其中包含一个 var id: Int?
字段。我想在 interface 或 superclass 中表达这一点,并让数据 classes 扩展它并设置它id
建造时。但是,如果我尝试这样做:
interface B {
var id: Int?
}
data class A(var id: Int) : B(id)
它抱怨我正在覆盖 id
字段,我是哈哈..
Q:如何让数据class A
在构造时取一个id
,并设置在 interface 或 superclass?
中声明的 id
确实,您不需要 abstract class yet. you can just override the interface 属性,例如:
interface B {
val id: Int?
}
// v--- override the interface property by `override` keyword
data class A(override var id: Int) : B
一个interface has no constructors so you can't call the constructor by super(..)
keyword , but you can using an abstract class instead. Howerver, a data class can't declare any parameters on its primary constructor,所以会覆盖超类的字段,例如:
// 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)
我有几个数据 classes,其中包含一个 var id: Int?
字段。我想在 interface 或 superclass 中表达这一点,并让数据 classes 扩展它并设置它id
建造时。但是,如果我尝试这样做:
interface B {
var id: Int?
}
data class A(var id: Int) : B(id)
它抱怨我正在覆盖 id
字段,我是哈哈..
Q:如何让数据class A
在构造时取一个id
,并设置在 interface 或 superclass?
id
确实,您不需要 abstract class yet. you can just override the interface 属性,例如:
interface B {
val id: Int?
}
// v--- override the interface property by `override` keyword
data class A(override var id: Int) : B
一个interface has no constructors so you can't call the constructor by super(..)
keyword , but you can using an abstract class instead. Howerver, a data class can't declare any parameters on its primary constructor,所以会覆盖超类的字段,例如:
// 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)