In the previous lesson, you learned about the if statement. That was a simple way to branch your
code. In this lesson, you will learn about the when statement and expression. A when is more
flexible way of branching than if, especially in the cases where you have multiple conditions to
check. The syntax of a when is more compact and easier to read than the cascade of else ifs.
The purpose of the program you will write in this lesson is exactly the same as in the previous one.
Basing on the grade given by the user as an input, a program should display a message describing
that grade. But now it will use the when statement instead of ifs to achieve the same result.
When Statement
The simplest form of the when statement is similar to the if statement. It is a series of
conditions to check with an optional else branch. The syntax is as follows:
Ef bpuvu ag uf uzco hvejpp, ah pmi lakpiwuihc venatv ojc hqu jihcozko tipoef, mxi rpif txexivezy
ut oltoapdoco.
When Expression
The body of the branches can also be an expression. The expression is the fragment of code that
returns a value. In that case, the entire when block is an expression. Take a look at the
following diagram:
Zula at e rvzsen uq zxu vzev atncufjiah:
val result = when {
condition1 -> value1
condition2 -> value2
else -> value3
}
When with the subject
The real benefit of the when statement or expression is that they can have a subject.
It is an argument that can be added to it in the parentheses. If it is present, each branch contains
a value to compare with it rather than a condition. The syntax is as follows:
A Kodeco subscription is the best way to learn and master mobile development. Learn iOS, Swift, Android, Kotlin, Flutter and Dart development and unlock our massive catalog of 50+ books and 4,000+ videos.