Error (or warning/inspection) on incompatible types when using ==


#1

I’m pleased to see that Kotlin has not adopted the Java way when it comes to .contains() in collections, i.e. instead of allowing Object as an argument regardless of the generic type signature of the collection, it is restricted to accepting only compatible types.

However, == does not have this behaviour, I can compare two objects of different unrelated subclasses without seeing errors or even inspections/warnings in IntelliJ. As a result, we’ve recently had some production issues as we migrated from one type to another, and some equality checks started to simply always return false.

Is there a particular reason for this design choice? And is there a way in IntelliJ or other code analysis tools to find all such usages of == - or plans to support some?


#2

== uses equals() and if you really wanted, you could implement equals so that it returns true even for “unrelated” classes, whatever that really means.

Of course an inspection still would make sense.


#3

I appreciate that it would not be feasible to change the semantics of the language at this stage, but was curious to hear if this was a conscious decision. For reference, .contains() in Kotlin does not accept object (Any) while the equivalent in Java does, while for the same reasons that you describe a collection of one type of objects could contain an object of a different type that is .equals() to it.