How do you define and use an enumeration in Scala?

Instruction: Explain the process of creating and utilizing enumerations in Scala.

Context: This question tests the candidate's ability to work with Scala's Enumeration class to define sets of named values, which are useful for representing a group of related constants in a type-safe way.

Updated

Scala supports the older Enumeration API and Scala 3's enum syntax. In existing code, an enumeration object defines values with an owner-specific Value type:

object DaysOfWeek extends Enumeration {
  val Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday = Value
}
def activity(day: DaysOfWeek.Value): String = day match {
  case DaysOfWeek.Saturday | DaysOfWeek.Sunday => "Go hiking"
  case _ => "Time to work"
}
@main def enumerationExample(): Unit = {
  assert(activity(DaysOfWeek.Saturday) == "Go hiking")
  assert(activity(DaysOfWeek.Monday) == "Time to work")
  val parsed = DaysOfWeek.values.find(_.toString == "Friday")
  assert(parsed.contains(DaysOfWeek.Friday))
  assert(DaysOfWeek.values.find(_.toString == "Unknown").isEmpty)
}

withName is another lookup API, but it throws when a name is unknown; the example deliberately returns an Option. Avoid persisting automatically assigned ordinals as a stable external contract unless changes are tightly controlled. A named value does not itself validate untrusted input. Enumeration API

For new Scala 3 code, enum can express a closed set of named cases and parameterized alternatives with more direct compiler support for exhaustive matching. Use the representation expected by the existing API and specify explicit wire/storage codes when compatibility requires them. Scala 3 enumerations

Related Questions