Skip to main content

Conditional statements

Rell has two conditional statements: if for branching on a boolean condition, and when for multi-way branching. Both also exist in expression form, described in Conditional expressions.

If statement​

An if statement executes a branch depending on whether its condition is true, with an optional else branch. A branch is either a single statement or a block.

val x = 5;
val y = 10;

if (x == 5) print('Hello');

if (y == 10) {
print('Hello');
} else {
print('Bye');
}

Chain conditions with else if:

function describe(x: integer): text {
if (x == 0) {
return 'Zero';
} else if (x == 1) {
return 'One';
} else {
return 'Many';
}
}

print(describe(1)); // One

When statement​

The when statement is similar to switch in C++ or Java, but uses the syntax of when in Kotlin. It branches on the value of an expression:

function describe(x: integer): text {
when (x) {
1 -> return 'One';
2, 3 -> return 'Few';
else -> {
val res = 'Many: ' + x;
return res;
}
}
}

print(describe(5)); // Many: 5

A case matches when x equals the case value; comma-separated values in one case match any of them. The else case runs when nothing else matched.

Cases can use both constants and arbitrary expressions. When the values are constants, the compiler checks that they're unique. With an enum type, values use simple names, not full names.

A form of when without an argument is equivalent to a chain of if ... else if:

function classify(x: integer, some_value: integer): text {
when {
x == 1 -> return 'One';
x >= 2 and x <= 7 -> return 'Several';
x == 11, x == 111 -> return 'Magic number';
some_value > 1000 -> return 'Special case';
else -> return 'Unknown';
}
}

print(classify(5, 0)); // Several

Cases take arbitrary boolean expressions, and multiple comma-separated expressions in one case are combined with OR.

Differences from the expression forms​

Both constructs behave the same in statement and expression position, including how block arms work, with these exceptions:

  • A conditional statement produces no value, so it doesn't have to be exhaustive. An if statement needs no else branch, and a when statement needs no else case.
  • A branch of a conditional statement is a plain statement or code block, and it produces no value. In expression position, an arm is an expression or a value block whose trailing expression is the arm's value.