Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Kotlin
Stage 5: Specialization

Part 09 / Topic 6 of 10

Equality in depth: == vs ===, and the hashCode contract

== calls .equals() — "same value?" === checks identity — "the exact same object in memory?" This is the reverse of Java, where == is identity and .equals() is structural; it's a common trip-up coming from Java, JavaScript or C#.

class Point(val x: Int, val y: Int)   // no equals/hashCode override -- uses Any's identity default

val p1 = Point(1, 2)
val p2 = Point(1, 2)
println("Point: p1 == p2: ${p1 == p2}, p1 === p2: ${p1 === p2}")
Point: p1 == p2: false, p1 === p2: false
Point: p1 == same: true, p1 === same: true

Two separately built Points are not ==-equal, because Point never overrode equals — Any's default falls back to identity. That's precisely the gap data class closes. (same is just p1 itself, assigned to a second name — both == and === are true because it really is the same object, not a separately built one with equal fields.)

The contract: if a.equals(b) is true, then a.hashCode() must equal b.hashCode(). Overriding only equals breaks it:

class BrokenCoupon(val code: String) {
    override fun equals(other: Any?): Boolean = other is BrokenCoupon && code == other.code
    // hashCode NOT overridden -- still identity-based
}
class FixedCoupon(val code: String) {
    override fun equals(other: Any?): Boolean = other is FixedCoupon && code == other.code
    override fun hashCode(): Int = code.hashCode()   // hash exactly the field equals() compares
}
BrokenCoupon equals: true
BrokenCoupon hashCode equal: false  <- contract violated
Set thinks brokenB is already present: false  <- should be true, isn't

FixedCoupon equals: true
FixedCoupon hashCode equal: true
Set correctly recognises fixedB as already present: true

String: s1 == s2: true, s1 === s2: false

brokenA and brokenB are "equal" by equals() but land in different hash buckets, so a HashSet/HashMap can't recognize they're the same value — exactly the bug a mismatched contract causes. The last two lines prove Strings compare structurally with == as expected, and that building the same text at runtime (via StringBuilder, not a compile-time constant) does give two genuinely different objects under ===.

Full program: examples/05_equality_in_depth.kt.

Done here? The practice set for Part 9 — including the solutions — is on the part page.

Search the guide