Comparing field of enum to another enum value


#1

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:


#2

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.


#3

@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 https://youtrack.jetbrains.com/issue/KT-22043


#4

This is a NASTY bug indeed as we just found it in our production code. We assumed that we were comparing values of the same enum type but it turned out we were comparing two different enums with the same name and schema. This condition was used to filter data. Now we have to go back a long time and selectively reconstruct data and use the right filter to process them. We are talking about possibly weeks of patch work and even then we are not sure if the data can be totally fixed.