属性包含/排除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屋!
查看全文