liveBook · Manning

Hash code contract

As explained in Kotlin in Action, 2E

The hash code contract requires equal objects to produce the same hash code.

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

How Kotlin in Action, 2E covers it

How deep it goes
Traces HashSet lookup from hash-code comparison to value comparison and supplies a concrete implementation.
Examples
Uses two equal Alice Customer instances, a processed HashSet, and a name-and-postal-code hash calculation.
What you can do after
Diagnose and fix HashSet lookup failures by implementing hashCode consistently with equals.
How it connects
Connects hashCode with equals, HashSet, object methods, and Kotlin compiler-generated methods.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Kotlin in Action, 2E. The section links point to the parts of the book it draws on.