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:

1 Like

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

1 Like

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.

Is it an option to avoid such situations by using type safety?

Yes, since 1.4 comparing enum values of different types will be reported as error.

Not yet. I have the last version fo Kotlin in Android Studio.
In Kotlin Playground, if I run

enum class Color {
  RED, ORANGE, YELLOW, GREEN, BLUE, INDIGO, VIOLET}
enum class Texture {SOFT,HARD}
var cor = Color.RED
  var text = Texture.SOFT
  if (cor!=text)  println("ugh")

It prints uhg, it should throw an exception, isn’t it?

It should be a compilation error since Kotlin 1.4 and in 1.3.x it’s a warning.

1 Like

You are right. The last stable version in Android Studio is Kotlin 1.3. I didn’t know it.