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






