match expression for pattern matching. It works both on types and on expressions.
match for union types
Pattern matching on union types is used in message handling.
match on a union must be exhaustive: all alternatives must be covered.
else is not allowed for unions, but is permitted for a lazy match.
Syntax details
-
After
=>, one of the following is allowed:- a block:
A => { ... }; - an expression:
A => 123; - a return statement:
A => return SOME_EXPR; - a throw statement:
A => throw ERR_CODE.
- a block:
-
A comma is:
- optional after a block:
A => { ... } B => { ... }; - required in all other cases:
A => 1, B => 2.
- optional after a block:
-
A
matchcan be used as an expression:return match (v) { ... }. -
Variable declarations are allowed inside:
match (val v = ...).
match as expression
match can be used in expression position. In this form, it can be:
- assigned to a variable:
var smth = match (v) { ... }; - returned from a function:
return match (v) { ... }.
Variables declaration
A variable may be declared directly in thematch expression.
match for expressions
match can be used with constant expressions, similar to switch:
- Only constant expressions are allowed before
=>. elseis required whenmatchis used as an expression.elseis optional whenmatchis used as a statement.
match for enums
Pattern matching on enums requires exhaustive coverage of all cases:
else to handle the remaining values: