Kotlin if
and when
Expressions
In most programming languages if
and switch
are known as control flow statements, but in Kotlin if
and when
(the equivalent of switch
) can be used as expressions as well. Let’s explore what this means.
What is a Statement?
A statement is a syntactic unit of instructions to the computer. This is a prime characteristic of imperative programming languages. The unit of instructions let the computer know-how to achieve something step by step. Programs written in imperative programming languages are a sequence of one or more statements, i.e. multiple instruction sets to be executed one after the other.
What is an Expression?
An expression is a synthetic unit that returns a value. Unlike languages like Java, if
and when
in Kotlin can return a value and therefore can be used both as traditional control flow statements or as expressions. Let’s look at some examples.
Used as an expression, the control flow returns a value.
The code snippet above shows how the if
expression produces a value and returns it. The if
expression compares the values a
and b
and assigns the produced value to the variable maxValue
.
When using if
as an expression, there must always be an else
branch. If not, the compiler throws an error — ‘if’ must have both main and ‘else’ branches if used as an expression.
Similarly, when
should also always have an else
branch when used as an expression. See the example below.
To summarise, in Kotlin if
and when
can be used as either statements or expressions. A statement is a set of instructions given to the computer to get something done whereas expression is a synthetic unit that produces a value.