Equals Always Returns
ID |
kotlin.equals_always_returns |
Severity |
high |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Kotlin |
Tags |
correctness, equals |
Description
Reports equals() implementations whose body always returns a constant true or false.
An equals() that unconditionally returns a constant violates the Any.equals contract and
makes collection membership, deduplication, and comparisons unreliable for instances of the class.
Rationale
// Bad — always equal, any two instances compare as equal
override fun equals(other: Any?) = true // FLAW
// Bad — never equal, objects are never found in sets or maps
override fun equals(other: Any?): Boolean {
return false // FLAW
}
// Good — real structural comparison
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Widget) return false
return id == other.id
}
Remediation
Implement structural equality by comparing the meaningful fields of the class.
Always override hashCode() consistently: objects that are equals must have the same hashCode.