Search code examples
javascalacollectionsenums

Are there Scala 3 Specific enum Equivalents of Java's EnumSet/EnumMap?


Specifically using the new enum keyword provided by Scala 3...

enum Translation(val bit: Byte):
   case FlipX extends Translation(1)
   case FlipY extends Translation(2)
   case RotateClockwise extends Translation(4) //90 degrees

...What are the Scala 3 idiomatic style options to achieve the equivalent of Java's java.util.EnumSet and java.util.EnumMap?

I'm explicitly excluding any Scala 2 style approaches, including Enumeratum (performance consideration).


Solution

  • I think you have mentioned almost all approaches except using Java java.util.EnumSet and java.util.EnumMap themselves. New Scala 3 you can easily define enums that are compatible with Java, by extending java.lang.Enum.

    enum Translation(bit: Byte) extends java.lang.Enum[Translation] {
      case FlipX extends Translation(1)
      case FlipY extends Translation(2)
      case RotateClockwise extends Translation(4) // 90 degrees
    }
    
    object Translation {
      val translations = util.EnumSet.of(Translation.FlipX, Translation.RotateClockwise)
    }
    

    But in general, the approaches you mention in the question or simply a set or a map are usually used. Also, helpers defined in the enum itself cover most cases:

    Translation.values // all enum values
    Translation.fromOrdinal(1) // by byte
    Translation.valueOf("FlipX") // by name