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

查看:35
本文介绍了在 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() 方法的冲突而失败.只在一个类中留下 data 注释也不起作用.

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 注释只处理构造函数中声明的属性.也就是说,我必须声明所有父级的属性 open 并覆盖它们,这很丑陋:

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天全站免登陆