Avoid Referential Equality

ID

kotlin.avoid_referential_equality

Severity

high

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Kotlin

Tags

correctness, equality

Description

Reports use of referential equality operators (=== and !==) where structural equality (== and !=) should be used instead.

For data classes, strings, and other value-semantic types, === compares object identity rather than content. Two objects that are equal by value may not be identical by reference, causing unexpected false results.

Rationale

Referential equality is rarely what the developer intends for value types:

// Bad — identity comparison, may return false even for equal values
data class Point(val x: Int, val y: Int)

val p1 = Point(1, 2)
val p2 = Point(1, 2)
p1 === p2  // FLAW — false, different instances
p1 == p2   // true — structural equality

val a = "hello"
val b = "hello"
a === b  // FLAW — implementation-dependent

// Good — structural equality
a == b   // always true when values are equal

Remediation

Replace === with == and !== with !=. Kotlin’s == calls equals() and handles null safely.

References