EnumMap for Scala 3 enums

Are there any plans for a specialized map type for enums (similar to java.util.EnumMap)? Enums are often used to better organize simple sets of properties. For example, instead of

trait Pixel:
  val red: Byte
  val green: Byte
  val blue: Byte

One can write

trait Pixel:
  val brightness: Map[Color, Byte]

enum Color:
  case Red, Green, Blue

The latter prevents code duplication for each color by making them first-class. It also allows reuse of colors in other similar type definitions.

However, without a specialized map implementation for enums, it leads to overhead that can be prohibitive.

I guess it should be possible to build an EnumMap on top of the exisiting IntMap.

import scala.jdk.CollectionConverters.given
import scala.collection.mutable

trait Pixel:
  val brightness: mutable.Map[Color, Byte]

object Pixel:
  def emptyColorMap: mutable.Map[Color, Byte] =
    java.util.EnumMap(classOf[Color]).asScala

enum Color extends Enum[Color]: // java.lang.Enum is imported by default
  case Red, Green, Blue

I think you can make an immutable wrapper as well with the copy constructor of EnumMap

2 Likes

Thank you for the implementation proposals. I myself would have reimplemented it using an array internally. But if java.util.EnumMap can be used with a few little-known tricks, then that’s easier.

However, this is not what my post was really about (I would have posted on users.scala-lang.org, otherwise). I was asking about plans to add it to the standard library, as it seems to me that enums are incomplete without it.

I would expect most Scala users to default to more ugly code, or reimplement a worse version of EnumMap, rather than discover how to get java.util.EnumMap to work for their Scala enums.

2 Likes

also java EnumMap is not suitable for Scala.js/Native I assume

1 Like

It hasn’t been implemented, but it could.

1 Like