Why this matters
- Missing
breakis one of the oldest bug sources in C-family languages, and switch expressions remove the possibility entirely. - Exhaustiveness means adding an enum constant breaks the build rather than silently falling into
default. - Embedded JSON, SQL and HTML are everywhere, and escaped single-line strings make them unreadable and error-prone.
The old switch statement
Loading compiler…
Four problems: the variable must be declared outside and uninitialised, each case needs an explicit break, each
grouped label needs its own line, and the whole thing is a statement so it cannot be used inline.
Switch expressions
Loading compiler…
Old switch statement
case + breakForget break and it falls through
Assigns to a variableCannot be final
Switch expression
case A -> valueNo fall-through
Returns a valueAssign directly to a final variable
ExhaustiveCompiler checks every case
What the arrow form changes
- No fall-through. Each arm runs only its own branch, so
breakis gone. - Multiple labels per arm, comma-separated.
- It is an expression, so it can be assigned, returned, or passed as an argument.
- Exhaustiveness is required when it produces a value. Over an enum, covering every constant is enough and
defaultis unnecessary.
Loading compiler…
Multi-line arms with yield
When an arm needs more than one statement, use a block and yield the value.
Loading compiler…
The rest of this guide is part of Pro
Free covers every fresher guide in full. Pro unlocks Senior, Staff and Architect guides across every track.
Still to come · 4 sections
- The colon form still exists
- Switch on what
- Text blocks
- Common misreadings
Test yourself
Answer these before moving on — recall is what makes it stick.