liveBook · Manning

Hash value

As explained in Kotlin in Action, 2E

hashCode is an object method that returns an integer hash value consistent with the object's equality semantics.

A hash value is the integer returned by an object's hashCode method. Hash-based containers such as HashSet and HashMap use it to locate objects efficiently, so equal objects must produce matching hash values. section 4.3 section 4.3.2

Implementing hashCode alongside equals

If Customer defines equality using name and postalCode, its hash value should depend on the same properties:\n\nclass Customer(val name: String, val postalCode: Int) {\n override fun equals(other: Any?): Boolean {\n if (other == null || other !is Customer) return false\n return name == other.name && postalCode == other.postalCode\n }\n\n override fun hashCode(): Int = name.hashCode() * 31 + postalCode\n}\n\nWithout the hashCode override, two separately created customers with equal data can fail a hash-set lookup. The equality and hash calculations must therefore be maintained together. section 4.3.1

Kotlin reduces the maintenance burden in two common ways:

  • A data class automatically generates equals and hashCode from every property declared in the primary constructor. section 4.3.2
  • Properties outside the primary constructor do not affect generated equality or hash-code calculation. section 4.3.2
  • Read-only properties are strongly recommended when instances serve as hash-based container keys; mutation can leave a container in an invalid state. section 4.3.2
Listing 4.28 The Customer data class has implementations for all standard methods
fun main() {
   val c1 = Customer("Sam", 11521)
   val c2 = Customer("Mart", 15500)
   val c3 = Customer("Sam", 11521)
   println(c1)
   // Customer(name=Sam, postalCode=11521)
   println(c1 == c2)
   // false
   println(c1 == c3)
   // true
   println(c1.hashCode())
   // 2580770
   println(c3.hashCode())
   // 2580770
}

Compare equal Customer instances and observe that the generated hashCode values match. section 4.3.2

How Kotlin in Action, 2E covers it

How deep it goes
Defines manual and generated implementations, then warns how mutable keys can invalidate hash-based containers.
Examples
Uses a Customer class, a manual name-and-postal-code hash, hash-set lookup, and generated data-class results.
What it assumes
Assumes basic Kotlin classes and properties while introducing universal object methods and hash-based containers.
What you can do after
Apply hashCode correctly when overriding equals or declare a data class for generated equality and hash behavior.
How it connects
Connects hashCode with equals, data classes, HashMap, HashSet, and object immutability.

Also explained in

Compare how 7 books explain hash value →

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.