When In Kotlin

How To Articles

Kotlin is a modern programming language that has gained significant popularity among developers in recent years. One of the key features of Kotlin is its “when” expression, which provides a concise and powerful way to handle multiple conditions. In this article, I will delve deep into the “when” expression in Kotlin and share my personal experiences and insights.

Introduction to the “when” expression

The “when” expression in Kotlin is similar to the “switch” statement in other programming languages like Java. However, it offers more flexibility and expressiveness. With the “when” expression, you can match a value against multiple conditions and execute different blocks of code based on the matched condition.

Here’s a simple example to illustrate how the “when” expression works:

val day = 5
when (day) {
1 -> println("Monday")
2 -> println("Tuesday")
3 -> println("Wednesday")
4 -> println("Thursday")
5 -> println("Friday")
else -> println("Weekend")

In the above code, we have a variable “day” with a value of 5. The “when” expression checks the value of the “day” variable and executes the corresponding block of code based on the matched condition. In this case, it prints “Friday” to the console.

Using ranges in the “when” expression

The “when” expression in Kotlin also supports the use of ranges. Ranges allow you to match a value against a range of values. This can be particularly useful when dealing with numeric or character ranges.

Let’s consider an example:

val age = 25
when (age) {
in 0..17 -> println("You're under 18")
in 18..64 -> println("You're an adult")
in 65..Int.MAX_VALUE -> println("You're a senior citizen")
else -> println("Invalid age")

In this code, we have a variable “age” with a value of 25. The “when” expression checks the value of “age” and matches it against the specified ranges. Based on the matched condition, it prints the corresponding message.

Using “when” as an expression

One of the powerful features of the “when” expression in Kotlin is that it can also be used as an expression. This means that it can return a value, which can be assigned to a variable or used in other expressions.

Here’s an example:

val dayOfWeek = when (day) {
1 -> "Monday"
2 -> "Tuesday"
3 -> "Wednesday"
4 -> "Thursday"
5 -> "Friday"
else -> "Weekend"

In this code, the “when” expression assigns the matching string value to the variable “dayOfWeek”. If the value of “day” is 5, the assigned value will be “Friday”. This allows us to make the code more concise and readable.


The “when” expression in Kotlin is a powerful tool that allows developers to handle multiple conditions in a concise and expressive way. With its support for ranges and the ability to be used as an expression, it offers great flexibility in writing clean and readable code. Personally, I find the “when” expression to be one of the standout features of Kotlin, making it a joy to work with.