String Referential Equality

ID

kotlin.string_referential_equality

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Kotlin

Tags

bug, reliability

Description

Reports use of the referential equality operators === and !== when at least one operand has a String type. Referential equality on strings is implementation-dependent (JVM interning may or may not collapse two literal-derived strings into the same object) and almost always reflects a bug.

Rationale

String is a value-semantic type: developers want to know whether two strings hold the same characters, not whether they point to the same JVM object. Kotlin’s structural equality operator == calls equals on the receiver and handles null safely, which is what the author intended in nearly every case.

val a = "hello"
val b = readLine() ?: ""

// Bad
a === b              // FLAW — referential equality on String
a !== b              // FLAW — referential equality on String

// Good
a == b               // OK — structural equality
a != b               // OK — structural inequality

Remediation

Replace === with == and !== with != whenever the operands are strings. If the intent really is to test object identity (for example in JVM-level diagnostics), add a comment explaining why.

References