what is the best approach when I want to compare o...
# announcements
t
what is the best approach when I want to compare only some fields (ignoring the values of some others) of two
data class
instances? One by one?
g
Only by writing (or generating) a function that compare required fields
👍🏻 1
l
Only put the fields you want to compare in the default constrator, the auto generated equal only compare these props.
g
Yes, this one more way, but you will loose other fields also in toString and copy, so it’s not always good solution
i
At basic level you could Easiest way is override
hashCode
and
equals
, however they are usually pain to maintain (one of the reasons why we have data classes in Kotlin) Another thing would be what @Leo Na suggested (should be good if you don’t use
toString
or want to override it) You could also store class properties in the list but this would only help you in very specific scenarios
Copy code
data class Foo(val name: String, val age: Int)
val properties = listOf(Foo::name, Foo::age)
properties.forEach { it.name }
On top of that you can use reflection to list object properties (and compare with another object)
instance::class.memberProperties.forEach { println(it.name) }
👍 1