Kotlin Q & A

 

What is the when expression in Kotlin?

The when expression in Kotlin is a powerful feature that serves as a replacement for the traditional switch statement found in languages like Java. It provides a concise and expressive way to handle multiple branches of execution based on the value of an expression.

The syntax of the when expression is straightforward. It consists of the when keyword followed by an expression in parentheses, and then a series of branch conditions enclosed in curly braces.

Each branch condition can be a constant value, a range, or even an arbitrary expression. Kotlin evaluates the expression passed to when and executes the code block corresponding to the first matching branch condition.

If none of the branch conditions match the expression, Kotlin executes the else branch, which is optional.

Additionally, when expressions can be used as a replacement for if-else chains, offering a more readable and concise alternative.

Here’s a basic example of a when expression in Kotlin:

kotlin

val x = 5
when (x) {
    1 -> println("x is 1")
    2 -> println("x is 2")
    in 3..5 -> println("x is between 3 and 5")
    else -> println("x is not 1, 2, or between 3 and 5")
}

In this example, Kotlin evaluates the value of x and executes the corresponding branch of code based on the matching condition. If no condition matches, it executes the else branch. The in keyword is used to specify a range of values.

These control flow structures and expressions contribute to Kotlin’s expressiveness and flexibility, enabling developers to write clear, concise, and maintainable code for a variety of programming scenarios.

Previously at
Flag Argentina
Brazil
time icon
GMT-3
Experienced Android Engineer specializing in Kotlin with over 5 years of hands-on expertise. Proven record of delivering impactful solutions and driving app innovation.