Ad space (banner)
๐ŸŽฏKotlin Lessons
Lesson 14 / 68

The when Statement

In this lesson you will learn how to branch on several values with a when statement in Kotlin, which reads more clearly than a chain of if statements. This is for anyone searching for "Kotlin when how to use".

A when statement corresponds to the switch of other languages. No break is needed, and each condition maps to its work with -> - a simple, characteristically Kotlin form.

The sample code prints a different message for 1 -> through 3 -> depending on day, falling back to "Other day" in else ->. Not needing a break at the end of each branch is characteristic of Kotlin.

A common stumbling block for beginners is not realising that when can also be used as an "expression". Used as a when expression it returns a value, so the result of the branch can be assigned straight to a variable.

In real-world development when statements are common wherever you branch on a fixed set of options, such as days of the week or status codes.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Kotlin directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)