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在接口或超类中声明的数据类?
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)
| 归档时间: |
|
| 查看次数: |
1687 次 |
| 最近记录: |