example:
data class Test(val name: String, val age: Int)
val a = Test("a", 21)
val b = Test("b", 31)
val result = a == b // false
want result
return true, what to do?
example:
data class Test(val name: String, val age: Int)
val a = Test("a", 21)
val b = Test("b", 31)
val result = a == b // false
want result
return true, what to do?
As per comments, it's not clear what you're aiming for here.
By default, two instances of data class
are considered equal when all the properties in their primary constructor are equal. So in the question, two Test
s will be equal when they have the same name
and age
:
println(Test("a", 1) == Test("a", 1)) // prints ‘true’
println(Test("a", 1) == Test("b", 1)) // prints ‘false’
println(Test("a", 1) == Test("a", 2)) // prints ‘false’
It looks like you want two Test
s to be considered equal when they have the same name
, even if they have different age
s. To do that, you have two main options:
Override their equals()
and hashCode()
* methods:
data class Test(val name: String, val age: Int) {
override fun equals(other: Any?) = other is Test && other.name == name
override fun hashCode() = name.hashCode()
}
That gives Test
a natural sense of equality, which will apply everywhere two Test
s are checked, whether you're using ==
, or putting them in a Set
, or whatever.
Check the names explicitly at that point in your code:
val result = a.name == b.name
Obviously, that will only apply to that particular check, and won't affect anything else. So it's simpler for this one case, but you'd have to remember to repeat it anywhere else you want to check for equality in that way.
Which you choose depends on what Test
means in your case, and whether checking only the name is the obvious, natural behaviour that you'll want by default.
(However, in the question, that will still result in a != b
, because a
and b
have different names as well as different ages.)
(* It won't give you an error if you fail to override hashCode()
as well, but that breaks the contract for equals()
and is likely to give strange behaviour, such as not being able to find Test
elements/keys you've added to sets/maps, errors or infinite loops when trying to sort a list of Test
s, and so on.)