Can I use guard expressions in switch statements and while loops, not just if?

← Control Flow · Ref: Q1022

Yes. Guard expressions work identically in if, switch, while, do-while, and try. The pattern is always 'v <- expression' which declares v and only enters the block if v is SET.

GUARD IN IF:

  if name <- findUser(userId)
    stdout.println(name)

GUARD IN SWITCH:

  switch record <- fetchRecord(recordId) with record
    case .category == "ACTIVE"
      processActive(record)
    default
      processOther(record)

GUARD IN WHILE:

  while item <- iterator.next()
    process(item)

GUARD IN TRY:

  try connection <- openDatabase()
    query(connection)
  catch
    -> ex as Exception
    handleError(ex)

All four patterns follow the same rule: the block only executes if the guard expression returns a SET value. The declared variable is only available inside the block.

Example

defines module qa.controlflow.guardsswitchwhile

  defines function

    lookupStatus() as pure
      -> code as String
      <- rtn as String: String()

      activeCode <- "ACT"
      pendingCode <- "PND"

      if code == activeCode
        rtn: "Active"
      else if code == pendingCode
        rtn: "Pending"

  defines program

    GuardsSwitchWhileDemo()
      stdout <- Stdout()

      //Guard in if
      if status <- lookupStatus("ACT")
        stdout.println(`Status: ${status}`)

      //Guard in if with else (unset path)
      if unknown <- lookupStatus("XXX")
        stdout.println(`Found: ${unknown}`)
      else
        stdout.println("Status not found")

      //Guard in switch
      switch found <- lookupStatus("PND") with found
        case == "Active"
          stdout.println("Is active")
        case == "Pending"
          stdout.println("Is pending")
        default
          stdout.println(`Other: ${found}`)

Common mistakes

E01073 — 'null' does not exist in EK9; an unset String is `String()`, not `null`, which triggers E01073 - use tri-state (unset/set) semantics. See ek9 -h E01073 for details.

Incorrect:

      <- rtn as String: null

Correct:

      <- rtn as String: String()
Other ways to ask this
  • Show me guards in a switch statement in EK9
  • How do guards work in while loops in EK9?
  • Do EK9 guards work in all control flow constructs?

Coming from another language?

EK9 guards are universal — same syntax in if, switch, while, and try. One pattern to learn, works everywhere.

Keywords: try, switch, while, guard, control flow, universal