When statement
In Rell, when
statement is similar to switch
in C++ or Java, but uses the syntax of when
in Kotlin. The when
expression is a versatile construct used for multi-way branching based on the value of an expression. It allows you to
define different cases and actions to be taken depending on the value of the given expression. Here's an example:
when(x) {
1 -> return 'One';
2, 3 -> return 'Few';
else -> {
val res = 'Many: ' + x;
return res;
}
}
In this example:
x
is the expression that is being evaluated in thewhen
statement. The value ofx
will determine which branch of thewhen
expression will be executed.1 -> return 'One';
: This line specifies the first case. Ifx
is equal to1
, the expression'One'
will be returned.2, 3 -> return 'Few';
: This line specifies the second case. Ifx
is either2
or3
, the expression'Few'
will be returned.else -> { ... }
: This is the default branch, executed when none of the previous cases match. It allows for more complex code to be executed. In this case:- A local variable
res
is declared to store the result. - The value of
x
is concatenated to the string'Many: '
using the+
operator. - The entire constructed string is stored in
res
. - Finally,
res
is returned.
- A local variable
Features
- It can use both constants as well as arbitrary expressions.
- When using constant values, the compiler checks that all values are unique.
- When used 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
:
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';
}
- Can use arbitrary boolean expressions.
- When you specify multiple comma-separated expressions, any triggers the block (combined via OR).
You can use both forms of when
(with and without an argument) as an expression:
return when(x) {
1 -> 'One';
2, 3 -> 'Few';
else -> 'Many';
}
- If you are using
when
as an expression, it must be exhaustive, theelse
statement can make it exhaustive. - You can use it in at-expression, in which case it's translated to SQL
CASE WHEN
...THEN
expression.