Sti*_*uck 1 overriding kotlin data-class
我尝试为我的一些数据类创建一个自定义的 toString() 方法。但我只想定义 fun toString 的覆盖一次。
这将是我的超级班:
abstract class Id(val value: String) {
override fun toString(): String {
return value
}
}
Run Code Online (Sandbox Code Playgroud)
现在我想通过扩展超类 Id 在我的一些数据类中使用自定义的 toString() 方法:
data class MyId(val v: String): Id(v)
Run Code Online (Sandbox Code Playgroud)
但是,这会在 MyId 中为“v”引入辅助字段和 getter,这不是我想要的。使用“value”而不是“v”给我带来了问题:“value”隐藏了超类型“Id”的成员。我想重用 Id 中定义的“值”字段和 getter。我不想介绍一个新的。
我该如何纠正?
我不太确定你想做什么,但你可以做到这一点
abstract class Id(open val value: String) {
override fun toString(): String {
return value
}
}
data class MyId(override val value: String): Id(value)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
542 次 |
| 最近记录: |