Switch Expressions
Switch expressions allow a switch to produce a value and support arrow labels that avoid accidental fall-through.
String category = switch (status) {
case NEW -> "pending";
case PROCESSING -> "active";
case COMPLETED -> "done";
case FAILED -> "error";
};
When multiple statements are needed before producing a value, yield can return the result from a block. Exhaustiveness is especially useful with enums and sealed hierarchies.
Key Takeaways
- Switch expressions return values.
- Arrow cases do not fall through by default.
- Exhaustiveness can improve safety for closed domains.