我有几个数据类,其中包括一个var id: Int?
字段。我想在接口或超类中表达这一点,并使数据类扩展它并在构造时设置此id
。但如果我尝试这样做:
interface B {
var id: Int?
}
data class A(var id: Int) : B(id)
它抱怨我正在覆盖id
字段,而事实上我的确是这样做了哈哈..
Q: 在这种情况下,我该如何让数据类A
在构造时接受一个id
,并设置在接口或父类中声明的那个id
?
我有几个数据类,其中包括一个var id: Int?
字段。我想在接口或超类中表达这一点,并使数据类扩展它并在构造时设置此id
。但如果我尝试这样做:
interface B {
var id: Int?
}
data class A(var id: Int) : B(id)
它抱怨我正在覆盖id
字段,而事实上我的确是这样做了哈哈..
Q: 在这种情况下,我该如何让数据类A
在构造时接受一个id
,并设置在接口或父类中声明的那个id
?
实际上,你还不需要一个抽象类(abstract class)。你可以直接重写(interface)的属性,例如:
interface B {
val id: Int?
}
// v--- override the interface property by `override` keyword
data class A(override var id: Int) : B
一个接口没有构造函数,因此您无法使用super(..)
关键字调用构造函数,但是您可以使用抽象类。然而,数据类不能在其主构造函数中声明任何参数,因此它将覆盖超类的字段,例如:
// 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)
interface B {
var id: Int?
}
data class A(override var id: Int?) : B
var a1:A = A(1)
var a2:A = A(null)
data class
扩展class
存在一些问题。所以我改变了思路,最终发现你只是想要实现接口getters/setters而已。 - holi-javaopen val
- is that right? Seems likeprotected final
- Abhijit Sarkarprotected
getter的private final
字段吗? - Abhijit Sarkar