https://kotlinlang.org logo
#announcements
Title
# announcements
t

thiagoretondar

07/06/2019, 1:47 AM
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

gildor

07/06/2019, 2:12 AM
Only by writing (or generating) a function that compare required fields
👍🏻 1
l

Leo Na

07/06/2019, 3:20 AM
Only put the fields you want to compare in the default constrator, the auto generated equal only compare these props.
g

gildor

07/06/2019, 6:47 AM
Yes, this one more way, but you will loose other fields also in toString and copy, so it’s not always good solution
i

igor.wojda

07/06/2019, 1:56 PM
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