扩展Kotlin中的数据类 [英] Extend data class in Kotlin

查看:123
本文介绍了扩展Kotlin中的数据类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

数据类似乎是Java中老式POJO的替代品。很可能这些类允许继承,但我看不到扩展数据类的便捷方法。我需要的是这样的:

Data classes seem to be the replacement to the old-fashioned POJOs in Java. It is quite expectable that these classes would allow for inheritance, but I can see no convenient way to extend a data class. What I need is something like this:

open data class Resource (var id: Long = 0, var location: String = "")
data class Book (var isbn: String) : Resource()

代码上面的失败是因为 component1()方法的冲突。仅在一个类中留下数据注释也不起作用。

The code above fails because of clash of component1() methods. Leaving data annotation in only one of classes does not do the work, too.

也许还有另一个成语扩展数据类?

Perhaps there is another idiom to extend data classes?

UPD:我可能只注释子子类,但 data 注释只处理声明的属性构造函数。也就是说,我必须声明所有父母的属性打开并覆盖它们,这是丑陋的:

UPD: I might annotate only child child class, but data annotation only handles properties declared in the constructor. That is, I would have to declare all parent's properties open and override them, which is ugly:

open class Resource (open var id: Long = 0, open var location: String = "")
data class Book (
    override var id: Long = 0,
    override var location: String = "",
    var isbn: String
) : Resource()


推荐答案

事实是:数据类在继承方面不能很好地发挥作用。我们正在考虑禁止或严格限制数据类的继承。例如,众所周知,无法在非抽象类的层次结构中正确实现 equals()

The truth is: data classes do not play too well with inheritance. We are considering prohibiting or severely restricting inheritance of data classes. For example, it's known that there's no way to implement equals() correctly in a hierarchy on non-abstract classes.

所以,我可以提供:不要对数据类使用继承。

So, all I can offer: don't use inheritance with data classes.

这篇关于扩展Kotlin中的数据类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆