The hash code contract requires equal objects to produce the same hash code. Kotlin classes that override equals should override hashCode as well, or hash-based collections can behave incorrectly. section 4.3.1
A Customer in a HashSet
class Customer(val name: String, val postalCode: Int) { override fun equals(other: Any?): Boolean { if (other == null || other !is Customer) return false return name == other.name && postalCode == other.postalCode } override fun hashCode(): Int = name.hashCode() * 31 + postalCode } val processed = hashSetOf(Customer("Alice", 342562)) println(processed.contains(Customer("Alice", 342562))) // true HashSet first compares hash codes and compares values only when those codes match. Without the matching hashCode implementation, equals can report true while contains reports false. section 4.3.1
Listing 4.26 Implementing hashCode() for Customer
class Customer(val name: String, val postalCode: Int) {
/* ... */
override fun hashCode(): Int = name.hashCode() * 31 + postalCode
}
Inspect the compact hashCode implementation for Customer. section 4.3.1
