Equality: == is not ===
Kotlin separates value equality from object identity.
| Operator | Question | Meaning |
|---|---|---|
a == b | Equal content? | Null-safe equals |
a != b | Different content? | Negated equality |
a === b | Exact same object? | Reference identity |
a !== b | Different objects? | Negated identity |
data class User(val id: Long, val name: String)
val first = User(1, "Ada")
val second = User(1, "Ada")
println(first == second) // true
println(first === second) // false
a == b behaves conceptually like a?.equals(b) ?: (b === null).
Rules a custom equals must follow
If you write equals yourself, it must behave predictably: an object equals itself; equality works in both directions; equality remains consistent across a chain of equal objects; and equal objects return the same hashCode.
Never mutate fields involved in equality while an object is a HashSet member or HashMap key. Its hash bucket may change, making the entry effectively unreachable.
Data classes
Data classes generate equality from properties declared in the primary constructor. Properties stored only in the class body are not automatically included.
data class User(val id: Long, val name: String) {
var selected: Boolean = false // excluded from generated equality
}
That may be correct, but decide it deliberately. Ask: should changing selected make these two users different for this use case?
Compose, RecyclerView diffing, StateFlow, caches, and tests may compare values. Incorrect equality can hide a real UI change or cause work when nothing meaningful changed.
Architect decision
A database row can be the same item while its visible content has changed. Two users with ID 7 may be the same user, but a changed name means the UI content is different. Decide separately what identifies an item and what counts as changed content.
== compares values by calling equals safely, even with nulls. === checks whether two variables point to the exact same object. In most business and UI code, use ==; use === only when reference identity itself matters.
Interview check
When should === be used?
Only when object identity itself matters, such as checking a specific singleton or diagnosing reference sharing. Business value comparison normally uses ==.