🎓 A1Learner
🔍
0 of 50 lessons completed

Scala Enums

An enum names a fixed set of choices for a value. A value from an enum can only be one of the listed choices.

Store a choice in a val

The Color enum lists three choices. The val holds one of them, and printing it shows the case name.

enum Color:
  case Red, Green, Blue

@main def main(): Unit =
  val chosen = Color.Green
  println(chosen)

Values lists every case in order

The values list holds the cases in the order they were written. The length of that list counts the cases.

enum Color:
  case Red, Green, Blue

@main def main(): Unit =
  println(Color.values.mkString(", "))
  println(Color.values.length)

Choose with if and ==

An enum value can be checked with == inside an if. Red means stop here, and any other choice takes the else path.

enum Color:
  case Red, Green, Blue

@main def main(): Unit =
  val first = Color.Red
  if first == Color.Red then
    println("Stop")
  else
    println("Go")
  val second = Color.Green
  if second == Color.Red then
    println("Stop")
  else
    println("Go")

Example

enum Size:
  case Small, Medium, Large

@main def main(): Unit =
  val chosen = Size.Large
  println(chosen)
  println(Size.values.mkString(", "))
  println(Size.values.length)
  if chosen == Size.Large then
    println("Biggest")
  else
    println("Not biggest")

Key points

  • Enum: a type that names a fixed set of choices, written with the enum word.
  • Case: one of the choices listed in an enum, such as Red in the Color enum.
  • Storing: an enum choice can be stored in a val, like any other value.
  • Printing: printing an enum value prints the name of its case.
  • Values: Color.values lists all the cases in the order they were written.
  • Counting: values.length gives the number of cases in the enum.

In this example, the Size enum lists three choices in order, and the chosen val holds Large. The values line prints all three names, and its length prints as 3. The if check compares the chosen value with Large, so the last line prints Biggest.

Note

enum values are compared with ==, the same sign used for numbers and strings.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Scastie

Exercise

What does Color.values.length give for an enum Color with the cases Red, Green, and Blue?