There is the following example in <https://play.ko...
# getting-started
p
There is the following example in https://play.kotlinlang.org/byExample/overview for Kotlin Data classes: https://play.kotlinlang.org/byExample/03_special_classes/01_Data%20classes It seems to me that this example violates the principle that when overriding the equals method you should also override the hashCode(). I'm I missing something?
r
Not necessarily.
hashCode
is overwritten due to data classes' characteristics. The difference is, that in the example
equals()
is based solely on
id
and
hashCode
uses
name
and
id
, both.
p
But in this example it is possible that two objects are equal (using the overridden equals() method) but have a different hashCode. Am I correct that this violates the contract between equals() and hashCode(): objects that are equal to each other must return the same hashCode
r
That's correct. It violates: _equals consistency_: objects that are equal to each other must return the same hashCode
p
For an example that is looked upon by many students learning the Kotlin language this is confusing.
2