On this page
article
Switch
SwitchExtension is a standalone multi-branch control-flow wrapper. It evaluates the selector and executes the matching branch, or a default branch if none match.
Switch
What it is
SwitchExtension is a standalone multi-branch control-flow wrapper. It evaluates the selector and executes the matching branch, or a default branch if none match.
When to use it
- Replacing long
if/else ifchains. - Routing events to handlers based on type or value.
- Configurable strategy selection.
API reference
| |
Parameters
| Parameter | Type | Description |
|---|---|---|
selector | Object? Function(T) | Returns a value matched against cases keys. |
cases | Map<Object?, Func1<T, R>> | Map of selector values to function branches. |
defaultCase | Func1<T, R>? | Optional branch used when no case matches. |
Examples
Basic example
| |
Real-world example
| |
Best practices
- Order cases from most specific to least specific.
- Provide a
defaultCaseunless you want unmatched inputs to throw. - Keep predicates side-effect free.
Common pitfalls
- Case order matters: The first matching case wins; overlapping predicates can hide later branches.
- No default case: If no predicate matches and there is no default, the switch throws.