https://kotlinlang.org logo
#intellij
Title
# intellij
k

Klitos Kyriacou

09/06/2023, 5:09 PM
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

Chris Lee

09/06/2023, 5:10 PM
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

Klitos Kyriacou

09/06/2023, 5:12 PM
No, it's
true
because of the overridden
equals
.
c

Chris Lee

09/06/2023, 5:12 PM
correct.
k

Klitos Kyriacou

09/06/2023, 5:18 PM
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

ephemient

09/06/2023, 5:38 PM
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

Jacob

09/06/2023, 6:22 PM
what does
println(b == a)
print?
false 1
a

Anton Mefodichev

09/08/2023, 10:27 AM
I have created a ticket to KTIJ project: https://youtrack.jetbrains.com/issue/KTIJ-26980
k

Klitos Kyriacou

09/08/2023, 10:48 AM
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