Instruction

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

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:

when {
  condition1 -> statement1
  condition2 -> statement2
  else -> statement3
}

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:

Vpasowutb rw Uynlebsiay Abbpodbeem Syuquyapl b + o = tihanq

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:

when (subject) {
  value1 -> statement1
  value2 -> statement2
  else -> statement3
}
See forum comments
Download course materials from Github
Previous: Introduction Next: Demo