equals casts its argument without checking its type, throwing instead of returning false
What it finds
equals(other: Any?) is called with objects of any type, and its contract asks for false when the other object is of another type. An equals that casts with other as Point without first checking the type throws ClassCastException instead, and a HashMap or list.contains holding objects of several types then fails at runtime.
Reported when equals casts its parameter with as and its body neither tests the type with is, nor compares classes (javaClass, ::class), nor catches exceptions.
From the rule's source, equals_unchecked_cast.rs.
class Point(val x: Int, val y: Int) { override fun equals(other: Any?): Boolean { if (this === other) return true other as Pointtx0 reports: other as Point throws when other is of another type return x == other.x && y == other.y } override fun hashCode() = 31 * x + y} class Checked(val x: Int) { override fun equals(other: Any?): Boolean { if (other !is Checked) return false return x == (other as Checked).x } override fun hashCode() = x} class SameClass(val x: Int) { override fun equals(other: Any?): Boolean { if (javaClass != other?.javaClass) return false other as SameClass return x == other.x } override fun hashCode() = x} class ByWhen(val x: Int) { override fun equals(other: Any?): Boolean = when (other) { is ByWhen -> x == other.x else -> false } override fun hashCode() = x} class Other(val x: Int) { fun equals(other: Any?, strict: Boolean): Boolean = (other as Other).x == x} Turn it on, off or suppress it
The rule runs from the strict tier up. To turn it on in a lower tier, give it a level in tx0.toml:
[rules]
"tx0/kotlin:equals-unchecked-cast" = "warning"To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:
// tx0: ignore[tx0/kotlin:equals-unchecked-cast] reason="..."tx0 explain tx0/kotlin:equals-unchecked-cast shows the same in the terminal. Found a false positive? Report it.