Skip to main content

If

if runs a block when its condition is true, and else runs another when it isn't:

let value = 10

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

elif checks another condition when the ones before it were false. else if means the same:

let temperature = 18

if (temperature < 10) {
println("cold")
} elif (temperature < 25) {
println("mild")
} else {
println("hot")
}

The colon form​

A branch with one statement can use a colon instead of braces, with its statement on the same line:

let value = 10

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

Binding inside if​

An if can bind a value that may be absent. The branch runs only if the value is there, and inside it the name is an ordinary value:

let createName() : string? = "Ada"

if (let name? = createName()) {
println("The name is ${name}")
}

if as an expression​

if ... then ... else chooses between two values. As a value, an if always needs its else, so there's a value whichever way the condition goes:

let number = 7
let message = if number % 2 == 1
then "it's odd"
else "it's even"

elif chains more conditions, like a chain of ternaries in other languages:

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