-1

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?

tao xu
  • 11
  • 1

1 Answers1

2

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 Tests 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 Tests to be considered equal when they have the same name, even if they have different ages. 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 Tests 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 Tests, and so on.)

gidds
  • 16,558
  • 2
  • 19
  • 26
  • Only primary constructor parameters of data class are used in equality comparison. https://kotlinlang.org/docs/data-classes.html#properties-declared-in-the-class-body – ocos Aug 14 '22 at 12:55
  • 1
    @ocos Ah yes, I knew that but didn't quite say it! Now clarified, thanks. – gidds Aug 14 '22 at 18:16
  • 1
    Defining `equals` and `hashCode` doesn't give a "natural ordering". You have to define `compareTo` for that. – Klitos Kyriacou Aug 15 '22 at 11:01
  • 1
    @KlitosKyriacou You're right too, of course! (My excuse is that I wrote my answer in a big hurry…) Thanks for that — I've made a further update. – gidds Aug 15 '22 at 13:08