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 (also requires default, E07320)
switch category case "A" stdout.println("Alpha") default stdout.println("Other")
ENUMERATED TYPES: NO EXCEPTION
A switch on an enumeration needs a default too, even when its cases list every value: the value switched on may be UNSET, and the default is what handles that (E07320 for a statement, E07330 for an expression). An enumeration switch must ALSO cover every value with its cases (E07310), so the default cannot stand in for a forgotten value.
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
#!ek9 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: every switch, statement or expression, enum or not, requires a default (E07320/E07330), because the value may be unset; an enum switch must also cover every value (E07310).
Keywords: E07330, case, default, exhaustive, expression, missing, required, switch