Skip to main content
Tolk supports a match expression for pattern matching. It is a powerful construct that applies both to types and expressions.

match for union types

Pattern matching for unions is a key to message handling.
Although it’s a general mechanism compatible with any union type:

match for a union must be exhaustive

In other words, all alternatives must be covered.
Note that else is not allowed for unions but is permitted for a lazy match.

Syntax details

  • After => there is
    • either a block: A => { ... }
    • or an expression: A => 123
    • or A => return SOME_EXPR
    • or A => throw ERR_CODE
  • A comma
    • optional after a block: A => {} B => {}
    • required otherwise: A => 1, B => 2
  • May be used as a match expression: return match (v) { ... }
  • Variable declarations are allowed inside: match (val v = ...)

Using match as an expression

Using match in expression position allows:
  • var smth = match (v) { ... }
  • return match (v) { ... }
  • and similar

Declaring variables inside match

match for expressions (not for types)

match can be used with constant expressions, similar to switch:
Rules:
  • only constant expressions may appear before =>
  • else is required for match expressions and optional for statements

match for enums

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