Skip to content

Control Flow

if health <= 0 {
die()
} else if health < 25 {
playLowHealthWarning()
} else {
heal()
}

Use expr is TypeName as a boolean condition:

if entity is Player {
entity.takeDamage(10.0)
}
let isEnemy = obj is Enemy
let either = a is Player || a is NPC

let status = health > 0 ? "alive" : "dead"

Pattern matching with exhaustiveness checking. Two forms:

when health {
0 => print("Dead")
1, 2, 3 => print("Critical")
0..25 => print("Low")
26..=100 => print("OK")
else => print("Overheal")
}
when result {
is Success(value) => print(value)
is Error(msg) => print("Error: " .. msg)
}
when health {
x if x < 0 => print("Invalid")
x if x < 25 => print("Critical: $x")
else => print("OK")
}
when result {
is Success(value) => {
print(value)
log(value)
}
is Error(msg) => print(msg)
}

Replaces if/else chains:

when {
health == 100 => print("Full")
health <= 0 => print("Dead")
else => print("Damaged")
}

while health > 0 {
tick()
}
for item in inventory {
print(item.name)
}
for i in 0..10 {
print(i) // 0 to 9
}
for i in 0..=10 {
print(i) // 0 to 10
}
break // exit loop
continue // skip to next iteration