How does Kotlin implement equals and hashCode?


#1

Hi,

I just want to understand little more on how equals() and hashCode() are generated by Kotlin.

Does Kotline default “class Foo” generates equals() and hashCode(), or is it only by when using “data class Foo”?

When Kotlin generates equals() and hashCode(), what implementation does it use? Can you document the pesudo code here?

Also how does Kotlin address the subclass with additional fields concern in regard to equals() and hashCode() implementation? More specifically, I am interested in knowing how Kotlin address the issue that Scala addressed with the “canEqual()” pattern described here: http://www.artima.com/lejava/articles/equality.html

Thanks,
Zemian


#2

By default, no specific equals and hashCode are generated (thus, they check object identity).

For data classes, hashCode and equals are based on property values. I’ll write algorithm steps in words instead of pseudocode:

hashCode:

  1. Calculate hashCode for each property declared as constructor parameter in current class
  2. Return h1 × 31n−1 + h2 × 31n−2 + … + hn


equals (let parameter be named that):

  1. Check if that is instance of our class (instanceof-check)
  2. For each property declared as constructor parameter in current class, check if this.prop1 equals to that.prop1 (by invoking equals method).


As I have already said in other thread, data class inheritance is not supported. If we support it, we’ll consider stricter algorithm for equals().