Can guard expressions be used in switch and while, not just if?
← Control Flow · Ref: Q975
Yes. Guard declarations work IDENTICALLY in if, switch, while, do-while, and try. The same 'v <- expression' pattern means 'declare v, check if SET, only proceed if SET' everywhere.
IN IF:
if name <- findUser(id) stdout.println(name)
IN SWITCH:
switch record <- database.get(id) with record case .type == "USER" processUser(record) default processOther(record)
IN WHILE:
while item <- iterator.next() process(item)
IN TRY:
try connection <- openDatabase() query(connection) catch -> ex as Exception logError(ex)
The guard pattern is universal — one syntax to learn, works everywhere. This eliminates 90-95% of null pointer exceptions across ALL control flow.
See Q971 for if guard details. See Q75 for switch guard details.
Example
defines module qa.controlflow.guardcontexts defines function <?- Returns a set or unset value based on input. -?> fetchValue() as pure -> key as String <- rtn as String: String() if key? rtn: "Value for " + key defines program GuardContextsDemo() stdout <- Stdout() // Guard in IF if greeting <- fetchValue("hello") stdout.println(`IF guard: ${greeting}`) // Guard in IF with else if missing <- fetchValue(String()) stdout.println("Should not print") else stdout.println("IF guard: skipped because unset") // Guard in SWITCH switch found <- fetchValue("test") with found case == "Value for test" stdout.println(`SWITCH guard: exact match`) default stdout.println(`SWITCH guard: ${found}`)
Common mistakes
E01073 — 'null' does not exist in EK9; check a value with the '?' isSet operator, not '!= null'. See ek9 -h E01073 for details.
Incorrect:
if key != null
Correct:
if key?
Other ways to ask this
- Where can I use the <- guard pattern in EK9?
- Does the guard declaration work in switch statements?
- Show me guards in while loops in EK9
- Is the if v <- expr guard universal across EK9 control flow?
Coming from another language?
Go: if err := f(); err != nil — only works in if. Rust: if let — only works in if/while. Swift: if let — only in if. EK9: guards work in if, switch, while, do-while, and try — truly universal.
Keywords: while guard, switch guard, guard, universal, try guard