Compare Value To Itself

ID

kotlin.compare_value_to_itself

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Kotlin

Tags

CWE:570, CWE:571, bug, reliability

Description

Reports comparisons whose two operands are the same identifier — x == x, x === x, or x.equals(x). Self-comparisons reduce to a constant value and almost always reflect a typo where the author meant to compare two distinct-but-similarly-named variables.

Rationale

A self-comparison is dead code: it returns true for ==, ===, and equals, and false for != and !==. The compiler cannot warn about this because syntactically the expression is well-formed. The typical cause is a refactor or copy-paste where one operand should have been renamed.

// Bad
if (x == x) { ... }       // FLAW — always true
if (x === x) { ... }      // FLAW — always true
if (x.equals(x)) { ... }  // FLAW — always true

// Good
if (x == y) { ... }
if (left.equals(right)) { ... }

Remediation

Inspect the comparison and replace one of the operands with the variable the author actually intended. If the comparison was deliberate (for a NaN check, for example), use the dedicated API: value.isNaN() for floating-point.