Why does a switch expression require a default case in EK9?
← Control Flow · Ref: Q788
When switch is used as an EXPRESSION (capturing its result), every possible input must produce a value. A missing default means some inputs have no result — the compiler rejects this.
SWITCH EXPRESSION (requires default)
label <- switch category <- rtn as String: String() case "A" rtn: "Alpha" default rtn: "Unknown"
SWITCH STATEMENT (default optional)
switch category case "A" stdout.println("Alpha")
EXCEPTION: ENUMERATED TYPES
When switching on an enumeration and all values are covered, no default is needed — the compiler knows the match is exhaustive.
THIS EXAMPLE
The describe() function uses switch as expression with a default case. The mutation removes the default.
See Q63 for switch basics. See Q73 for exhaustive enum switch. See Q782 for switch expressions.
Example
defines module qa.controlflow.switchdefault defines function describe() as pure -> category as String <- label as String? label: switch category <- rtn as String: String() case "A" rtn: "Alpha" case "B" rtn: "Beta" case "C" rtn: "Gamma" default rtn: "unknown category" defines program ShowCategories() stdout <- Stdout() stdout.println(describe("A")) stdout.println(describe("Z"))
Common mistakes
E07330 — A switch expression must handle all possible inputs. Without a default case, some values of category would produce no result. Add a default case to handle unmatched values. See ek9 -h E07330 for details.
Incorrect:
//no default case
Correct:
default rtn: "unknown category"
Other ways to ask this
- What triggers E07330 default required in switch expression?
- Why must switch expressions be exhaustive in EK9?
- How do I add a default case to a switch expression?
Coming from another language?
Java: switch expressions (14+) require exhaustive coverage or default. Python: match/case has no exhaustiveness check. Rust: match must be exhaustive (compiler enforced). Kotlin: when used as expression must be exhaustive. Go: switch statement only, no expression form. EK9: switch expression requires default unless enum is fully covered.
Keywords: missing, switch, E07330, default, case, required, exhaustive, expression