比较没有ID的Kotlin中的数据类 [英] Compare data class in Kotlin without ID

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

问题描述

我在Kotlin中有一个数据类,它具有许多属性,其中之一是ID.但是,当我在代码中实际使用compare函数时,在比较时我想排除此ID属性.除了手动添加compare函数外,还有什么方法可以做到这一点?

I have a data class in Kotlin, which has number of properties, one of which is ID. But when I actually use compare function in code, I would like to exclude this ID property when comparing. Is there any way to do that except manually boilerplating compare function?

推荐答案

您可以使用

You can use the copy() function on one of your data class instances to create a copy of it "altering some of its properties". e.g.:

data class User(val id: Long, val name: String)

val a = User(1, "John")
val b = User(2, "John")

println(a == b) // false
println(a.copy(id = b.id) == b) // true

创建一个数据类实例的副本并将其ID更改为与要比较的另一个实例相同的ID,可以有效地忽略该属性.

Creating a copy of one of your data class instances and altering the id to be the same as the other instance you want to compare against allows to effectively ignore that property.

您还可以复制两个数据类实例,并将id设置为某个公共值,但是如果您只进行一次性比较,则对copy()的调用将是不必要的.

You could also copy both data class instances and set id to some common value but if you are only doing one-off comparisons then this would be an unnecessary call to copy().

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

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