Hash Code and Copying Objects

Explore the hashCode method in Kotlin, its significance for data structures, and the benefits of the copy method in data classes.

The hashCode method

Another method from Any is hashCode, which is used to transform an object into an Int. With a hashCode method, the object instance can be stored in the hash table data structure implementations that are part of many popular classes, including HashSet and HashMap. The most important rule of the hashCode implementation are:

  • Consistency with equals: It should be consistent with equals, so it should return the same Int for equal objects, and it must always return the same hash code for the same object.

  • Uniform distribution: It should spread objects as uniformly as possible in the range of all possible Int values.

Default vs. data classes

The default hashCode is based on an object’s address in memory. The hashCode generated by the data modifier is based on the hash codes of this object’s primary constructor properties. In both cases, the same number is returned for equal objects.

Get hands-on with 1400+ tech skills courses.