Conditionals

An if expression specifies that some code should only be evaluated if a certain condition is true. For example:

script {
  fun example() {
    if (x > 5) x = x - 5
  }
}

The condition must be an expression of type bool.

An if expression can optionally include an else clause to specify another expression to evaluate when the condition is false.

script {
  fun example() {
    if (y <= 10) y = y + 1 else y = 10
  }
}

Either the "true" branch or the "false" branch will be evaluated, but not both. Either branch can be a single expression or an expression block.

The conditional expressions may produce values so that the if expression has a result.

script {
  fun example() {
    let z = if (x < 100) x else 100;
  }
}

The expressions in the true and false branches must have compatible types. For example:

If the else clause is not specified, the false branch defaults to the unit value. The following are equivalent:

Commonly, if expressions are used in conjunction with expression blocks.

Grammar for Conditionals

if-expressionif ( expression ) expression else-clauseopt

else-clauseelse expression