在 Kotlin 中重写子类中的变量
我有这个超类:
abstract class Node(rawId: String) {
open val id: String
init {
id = Base64.toBase64(this.javaClass.simpleName + "_" + rawId)
}
}
这个子类扩展了 Node:
data class Vendor (
override var id: String,
val name: String,
val description: String,
val products: List<Product>?
): Node(id)
当我像这样初始化 Vendor 类时:
new Vendor(vendor.getId(), vendor.getGroup().getName(), description, products);
我可以看到 Node 中的 init 块按预期被触发。但是,当我从 Vendor 对象获取 id 时,它是 rawId,而不是编码的 Id。
所以我对 Kotlin 类中的初始化顺序/逻辑有点困惑。我希望编码代码在所有子类中都是通用的。有更好的方法吗?
I have this super class:
abstract class Node(rawId: String) {
open val id: String
init {
id = Base64.toBase64(this.javaClass.simpleName + "_" + rawId)
}
}
And this subclass that extends Node:
data class Vendor (
override var id: String,
val name: String,
val description: String,
val products: List<Product>?
): Node(id)
When I initialize the Vendor class like this:
new Vendor(vendor.getId(), vendor.getGroup().getName(), description, products);
I can see the init block in Node get fired as expected. However, when I get the id from the Vendor object, it is the rawId and not the encoded Id.
So I am a bit confused about the initialization order/logic in Kotlin classes. I want the encoding code to be common across all subclasses. Is there a better way to do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题是因为您覆盖了子类中的 id 字段,因此它将始终保留 rawId 值。
由于基类已经有一个 id 字段,该字段必须是编码值,因此您不需要在子类中重写它。您需要将
rawId
提供给Vendor
类中的Node
类,并让基类处理id 要实例化的值。您可以将抽象类定义为
,然后将子类定义为
然后,
由于
Vendor
是Node
的子类,因此id
字段也可用到带有编码值的Vendor
对象。The problem is because you are overriding the
id
field in the subclass and hence it would always remain therawId
value.Since the base class has already an
id
field which has to be an encoded value, you don't need to override it in the subclass. You need to provide therawId
to theNode
class in yourVendor
class and let the base class take care of theid
value to be instantiated with. You can have your abstract class asand then define your subclass as
Then with
since
Vendor
is a subclass ofNode
, theid
field is also available to theVendor
object with the encoded value.