Kotlin 数据类的属性包含/排除 [英] Property include/exclude on Kotlin data classes
本文介绍了Kotlin 数据类的属性包含/排除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我只希望生成的 equals 和 hashCode 实现中包含一两个字段(或者可能排除一个或多个字段).对于一个简单的类,例如:
Suppose I only want one or two fields to be included in the generated equals and hashCode implementations (or perhaps exclude one or more fields). For a simple class, e.g.:
data class Person(val id: String, val name: String)
Groovy 有这个:
Groovy has this:
@EqualsAndHashCode(includes = 'id')
龙目岛有这个:
@EqualsAndHashCode(of = "id")
在 Kotlin 中这样做的惯用方法是什么?
What is the idiomatic way of doing this in Kotlin?
data class Person(val id: String) {
// at least we can guarantee it is present at access time
var name: String by Delegates.notNull()
constructor(id: String, name: String): this(id) {
this.name = name
}
}
只是感觉不对...我真的不希望 name
是可变的,而且额外的构造函数定义很丑陋.
Just feels wrong though... I don't really want name
to be mutable, and the extra constructor definition is ugly.
推荐答案
我用过这种方法.
data class Person(val id: String, val name: String) {
override fun equals(other: Person) = EssentialData(this) == EssentialData(other)
override fun hashCode() = EssentialData(this).hashCode()
override fun toString() = EssentialData(this).toString().replaceFirst("EssentialData", "Person")
}
private data class EssentialData(val id: String) {
constructor(person: Person) : this(id = person.id)
}
这篇关于Kotlin 数据类的属性包含/排除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文