The equals and hashCode methods

When dealing with data classes, there is often a need to compare two instances for structural equality (they contain the same data, but are not necessarily the same instance). We many simply want to check whether one instance of the User class equals another User instance or if two product instances represent the same product. A common pattern used to check whether objects are equal is to use an equals method that uses the hashCode method internally:

    product.equals(product2)  

The general contract for overridden implementations of hashCode is that two equal objects (according to the equals implementation) need to have the same hash code. The reason behind this is that hashCode is often compared before equals ...

Get Android Development with Kotlin now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.