I've just come across this error. Is it a known is...
# intellij
k
I've just come across this error. Is it a known issue?
Copy code
class A {
    override fun equals(other: Any?): Boolean {
        return true
    }
}
fun main() {
    val a = A()
    val b: A? = null
    println(a == b)  // It's always true, but IntelliJ warns it's always false
}
youtrack 2
c
that condition will always be false - its comparing an instance of
A
to
null
at least from IntelliJ’s perspective, which is static code anlysis, not execution of the code.
k
No, it's
true
because of the overridden
equals
.
c
correct.
k
Note that if you change it to
a.equals(b)
, then it doesn't give that warning. Also,
a.equals(null)
doesn't give a warning - which is correct, since
a == null
is not the same as
a.equals(null)
according to the language spec, but this only applies for the literal
null
. If it's a value that happens to be null, then
a == b
is always the same as
a.equals(b)
and therefore IntelliJ shouldn't give that warning.
e
that
equals
does not satisfy the contract
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-any/equals.html
Never equal to null: for any non-null value
x
,
x.equals(null)
should return false.
thank you color 1
2
note that Java has the same wording, so this is true for non-Kotlin classes as well https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#equals-java.lang.Object-
j
what does
println(b == a)
print?
false 1
a
I have created a ticket to KTIJ project: https://youtrack.jetbrains.com/issue/KTIJ-26980
k
Thanks, Anton. Given what ephemient has pointed out, I can see why IntelliJ thinks the condition is always false (it assumes
equals
would satisfy the contract). It would be more important to see an inspection about
equals
not satisfying the contract, if that's possible. I made a comment on the ticket.
thank you color 1