Skip to main content

Control Flow: if and match

if/else branches on a boolean condition:

if (value == 10) {
print("first branch")
} else {
print("second branch")
}

A single-statement branch can use a trailing colon instead of braces:

if (value == 10):
print("first branch")
else:
print("second branch")

Binding inside if​

An if can bind a value inline, which implicitly checks whether it's some rather than evaluating truthiness:

# Implicitly checks if the value is some.
if (let instance = createInstance()) {
# Executes if the value is some ...
}

# Equivalent to:
let instance = createInstance()
if (instance is some) {
print("The length of the text is ${length}")
}

if as an expression​

let number = ...
let message = if number.isOdd
then "it's odd"
else "it's even"

Chained conditions read like a ternary chain:

let result = if x < 20 then 10
elif x < 30 then 20
elif x < 50 then 30
else 100

match​

match is Nylon's pattern-matching construct. Unlike a chain of ifs, branches are jumped to directly, and it works over basic values, enums, strings, and type patterns:

let value = match(text) {
"true" -> 1
"false" -> 0
else -> raise Exception()
}

match! enforces exhaustiveness — the compiler requires every case to be handled, or it automatically raises if none match:

let number = ...
let value = match!(number) {
1 -> "one"
2 -> "two"
}