Loop while a connection value remains set, processing each iteration.

← Control Flow · Ref: Q1150

Use a while guard with declaration operator:

  while conn <- getConnection() with counter < maxIters
    stdout.println(conn)
    counter++

The guard re-evaluates on EVERY iteration. If getConnection() returns an unset value, the loop terminates cleanly. The 'with' clause adds an additional condition. See Q77 for while guard details. See Q971 for guard expressions.

Example

defines module qa.controlflow.whileguard

  defines class

    ConnectionSupplier
      remaining <- 0

      ConnectionSupplier()
        -> count as Integer
        this.remaining: count

      getConnection()
        <- rtn as String: String()
        if remaining > 0
          rtn: `Connection-${remaining}`
          remaining: remaining - 1

      override operator ? as pure
        <- rtn as Boolean: remaining?

  defines program

    WhileGuardDemo()
      stdout <- Stdout()

      supplier <- ConnectionSupplier(4)
      counter <- 0
      maxIters <- 10

      // Loop while getConnection() returns a SET value
      while conn <- supplier.getConnection() with counter < maxIters
        stdout.println(conn)
        counter: counter + 1

      stdout.println(`Processed ${counter} connections`)

Common mistakes

E07390 — Using a constant Boolean literal (true) as the while-guard's 'with' condition is a pointless expression; supply a real terminating condition instead. See ek9 -h E07390 for details.

Incorrect:

while conn <- supplier.getConnection() with true

Correct:

while conn <- supplier.getConnection() with counter < maxIters

E01073 — 'null' does not exist in EK9; use tri-state semantics (unset/set) with the '?' operator and guard expressions instead. See ek9 -h E01073 for details.

Incorrect:

counter <> null

Correct:

counter < maxIters
Other ways to ask this
  • Write code to use a while guard that loops while a value is set
  • I have a supplier that eventually returns unset and need to loop until that happens
  • Given a function that returns set values for N calls then unset, process each value
  • In Java I'd use while ((val = getNext()) != null). Write the EK9 guard equivalent

Coming from another language?

Java: while ((val = getNext()) != null) { process(val); }. Go: for val := getNext(); val != nil; val = getNext(). Rust: while let Some(v) = get_next(). EK9: while val <- getNext() — guard re-evaluates each iteration.

Keywords: guard, loop, while, poll, connection, declaration, unset, isset