Comparing field of enum to another enum value


In Android Studio this does not produce any warning:

class Stuff {

var field: EnumA = EnumA.OTHER_STUFF

fun isState() = field == EnumB.OTHER_STUFF


I understand that this is because == is actually using equals. But still, 99,9999% of the cases the user does not want to make this comparison. In Java we have a lint warning (when using equals() like this)
Just had a nasty bug due to this, very hard to see… Spent some time on it :sweat_smile:


What is the reasoning for not wanting to use equals in this case. The lint warnings about equals in Java are usually about the fact that the object you are calling equals on could be null leading to a null pointer exception.

That isn’t an issue here in Kotlin because we have nullability in the type system so the compiler knows if field can be null and because a == b in Kotlin is translated to a?.equals(b) ?: (b === null) which works if either a or b is null.

It isn’t an issue of performance either if the writer of the equals method follows the standard guidelines of checking for referential equality before evaluating the contents. The equals method for an enum ONLY checks referential equality.

So you would have to be specific on what the nasty bug is you are trying to prevent.


@dalewking Here the field of type EnumA is compared to a value of type EnumB which always returns false.

This looks like a bug, given that we prohibit using equality operator on pairs of other unrelated types, for example "" == StringBuilder() will result in compilation error.

UPD: And here is the bug