Skip to main content
Tolk supports a 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.
This is a general mechanism compatible with any union type:
A 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 comma is:
    • optional after a block: A => { ... } B => { ... };
    • required in all other cases: A => 1, B => 2.
  • A match can 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 the match expression.

match for expressions

match can be used with constant expressions, similar to switch:
Rules:
  • Only constant expressions are allowed before =>.
  • else is required when match is used as an expression.
  • else is optional when match is used as a statement.
All comparable types are supported, including addresses and enums.

match for enums

Pattern matching on enums requires exhaustive coverage of all cases:
Alternatively, use else to handle the remaining values: