Use an enumeration value in a switch statement to select behaviour.

← Enumerations · Ref: Q1170

Qualify enum values with the type name in switch cases:

  switch priority
    case Priority.HIGH
      label: "Urgent"
    case Priority.MEDIUM
      label: "Normal"

No fallthrough -- each case is independent. See Q1151.

Example

defines module qa.enumerations.enumguard

  defines type

    Priority
      HIGH
      MEDIUM
      LOW

  defines program

    EnumGuardDemo()
      stdout <- Stdout()

      priorities <- [Priority.HIGH, Priority.MEDIUM, Priority.LOW]

      for priority in priorities
        label <- "Unknown"
        switch priority
          case Priority.HIGH
            label: "Urgent"
          case Priority.MEDIUM
            label: "Normal"
          case Priority.LOW
            label: "Can wait"
          default
            label: "Unknown"
        stdout.println(`${priority}: ${label}`)

Common mistakes

E01010 — EK9 enums must be qualified with the type name: Priority.HIGH, not just HIGH.

Incorrect:

      case HIGH:

Correct:

      case Priority.HIGH
Other ways to ask this
  • I need to switch on an enum value and handle each case
  • In Java I'd use switch on an enum. Write the EK9 enum switch pattern
  • Given a Priority enum, map each value to a label using switch
  • Dispatch on enumeration values using switch with case

Coming from another language?

Java: switch(priority) { case HIGH: ... }. Kotlin: when(priority) { HIGH -> ... }. EK9: switch priority / case Priority.HIGH.

Keywords: enum, case, enumeration, dispatch, value, switch