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

1

1

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).

Leesa answered 19/5, 2024 at 19:14 Comment(3)
What specifically are you looking for in EnumSet and EnumMap? What's wrong with a regular Set or Map?Shannonshanny
Performance? Please see link after Enumeratum reference?Leesa
I mean just use BitSet and IntMapDishcloth
S
4

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
Sperry answered 19/5, 2024 at 21:45 Comment(1)
Scastie of this Answer: scastie.scala-lang.org/Lu8UtokFTKmcBsoBLTTZtQLeesa

© 2022 - 2025 — McMap. All rights reserved.