Skip to main content
ubuntuask.com

Back to all posts

How to Use the 'When' Expression In Kotlin?

Published on
6 min read
How to Use the 'When' Expression In Kotlin? image

Best Kotlin Programming Guides to Buy in October 2025

1 Functional Programming in Kotlin by Tutorials (First Edition): A Practical Approach to Writing Safer, More Reliable Apps

Functional Programming in Kotlin by Tutorials (First Edition): A Practical Approach to Writing Safer, More Reliable Apps

BUY & SAVE
$59.99
Functional Programming in Kotlin by Tutorials (First Edition): A Practical Approach to Writing Safer, More Reliable Apps
2 Kotlin Coroutines by Tutorials (Third Edition): Best Practices to Create Safe & Performant Asynchronous Code With Coroutines

Kotlin Coroutines by Tutorials (Third Edition): Best Practices to Create Safe & Performant Asynchronous Code With Coroutines

BUY & SAVE
$59.99
Kotlin Coroutines by Tutorials (Third Edition): Best Practices to Create Safe & Performant Asynchronous Code With Coroutines
3 Kotlin Apprentice (Third Edition): Beginning Programming with Kotlin

Kotlin Apprentice (Third Edition): Beginning Programming with Kotlin

BUY & SAVE
$59.99
Kotlin Apprentice (Third Edition): Beginning Programming with Kotlin
4 Data Structures & Algorithms in Kotlin (Second Edition): Implementing Practical Data Structures in Kotlin

Data Structures & Algorithms in Kotlin (Second Edition): Implementing Practical Data Structures in Kotlin

BUY & SAVE
$59.99
Data Structures & Algorithms in Kotlin (Second Edition): Implementing Practical Data Structures in Kotlin
5 Programming Android with Kotlin: Achieving Structured Concurrency with Coroutines

Programming Android with Kotlin: Achieving Structured Concurrency with Coroutines

BUY & SAVE
$48.00 $65.99
Save 27%
Programming Android with Kotlin: Achieving Structured Concurrency with Coroutines
6 Reactive Programming with Kotlin (Second Edition): Learn RX with RxJava, RxKotlin and RxAndroid

Reactive Programming with Kotlin (Second Edition): Learn RX with RxJava, RxKotlin and RxAndroid

BUY & SAVE
$59.99
Reactive Programming with Kotlin (Second Edition): Learn RX with RxJava, RxKotlin and RxAndroid
7 Kotlin in Action

Kotlin in Action

BUY & SAVE
$34.71 $44.99
Save 23%
Kotlin in Action
8 Android Fundamentals by Tutorials (First Edition): Build Android Apps With Kotlin & Jetpack Compose

Android Fundamentals by Tutorials (First Edition): Build Android Apps With Kotlin & Jetpack Compose

BUY & SAVE
$59.99
Android Fundamentals by Tutorials (First Edition): Build Android Apps With Kotlin & Jetpack Compose
+
ONE MORE?

In Kotlin, the when expression is used as a replacement for the traditional switch-case statement in other programming languages. It is a versatile and powerful tool for handling multiple conditions in a concise and readable way.

The basic syntax for using the when expression is as follows:

when (variable) { value1 -> { // code block executed when variable matches value1 } value2 -> { // code block executed when variable matches value2 } else -> { // code block executed when variable does not match any of the above values } }

Here, variable represents the value or expression to be evaluated against different cases. Each value is compared with the variable, and when a match is found, the corresponding code block is executed. If none of the values match, the code block under else is executed.

Additionally, the when expression supports multiple conditions in a single code block by separating them with a comma. For example:

when (variable) { value1, value2 -> { // code block executed when variable matches either value1 or value2 } value3 -> { // code block executed when variable matches value3 } else -> { // code block executed when variable does not match any of the above values } }

Furthermore, the when expression can also be used without an argument. In this case, it acts as an alternative to if-else if chains. For example:

when { condition1 -> { // code block executed when condition1 is true } condition2 -> { // code block executed when condition2 is true } else -> { // code block executed when none of the conditions are true } }

The when expression in Kotlin is not limited to fixed values or conditions. It can also be used with more complex expressions, ranges, types, and even custom classes to handle different cases in a flexible manner.

Overall, the when expression is a powerful feature of Kotlin that simplifies conditional expressions and enhances code readability.

How to use the 'when' expression with sealed classes in Kotlin?

To use the when expression with sealed classes in Kotlin, follow these steps:

  1. Define a sealed class by using the sealed modifier before the class declaration. This ensures that all subclasses of the sealed class are declared within the same file.

sealed class Result

  1. Create subclasses of the sealed class using the object or data keyword.

data class Success(val message: String) : Result() data class Error(val code: Int) : Result()

  1. Use the when expression to handle different cases based on the subclasses of the sealed class.

fun handleResult(result: Result) { when (result) { is Success -> println("Success: ${result.message}") is Error -> println("Error: ${result.code}") } }

In the above example, the handleResult() function takes a parameter of type Result (the sealed class). Inside the when expression, you can use is to check the type of the result parameter and perform different actions accordingly.

Note that when using sealed classes with when, if you handle all the subclasses, you don't need an else branch as the when expression is exhaustive.

How to handle exhaustive 'when' expressions in Kotlin?

In Kotlin, when expressions are a powerful way to handle exhaustive conditions by matching an expression against multiple possible values. However, there are cases when you need to handle a large number of possible values, which can make the code cumbersome to write and read. To handle such exhaustive expressions more efficiently, you can follow these approaches:

  1. Use ranges: If the possible values are sequential, you can use ranges in place of individual values. For example:

when (x) { in 1..10 -> println("Value between 1 and 10") in 11..20 -> println("Value between 11 and 20") // ... }

  1. Group values using commas: If some values have the same response, you can group them together separated by commas. For example:

when (x) { 1, 2, 3 -> println("Value is 1, 2, or 3") 4, 5, 6 -> println("Value is 4, 5, or 6") // ... }

  1. Use 'else' clause: If there are remaining values that don't fit into any specific conditions, you can use the 'else' clause to handle them. It acts as a catch-all for unmatched values. For example:

when (x) { in 1..10 -> println("Value between 1 and 10") in 11..20 -> println("Value between 11 and 20") else -> println("Value out of range") }

  1. Create named constants: If the exhaustive conditions are repeated in multiple places, you can define named constants to keep the code clean and maintainable. For example:

val RANGE_1_TO_10 = 1..10 val RANGE_11_TO_20 = 11..20

when (x) { in RANGE_1_TO_10 -> println("Value between 1 and 10") in RANGE_11_TO_20 -> println("Value between 11 and 20") // ... }

By utilizing these techniques, you can handle exhaustive 'when' expressions in a more concise and readable manner.

What is the difference between 'when' and 'switch' statements in Java?

In Java, both when and switch are control flow statements that allow you to perform different actions based on different conditions. However, there are some key differences between the two:

  1. Syntax: switch statements use the syntax: switch (expression) { case value1: // code block break; case value2: // code block break; default: // code block } when statements use the syntax: when (expression) { value1 -> result1 value2 -> result2 else -> result }
  2. Expression type: switch statements can use a byte, short, char, or int (primitive types) and also strings and enums as the expression. when statements support any type of expression, including primitive types, strings, enums, and objects.
  3. Matching conditions: switch statements use exact matching conditions (==) for primitive types and enums, and equals() method for strings. when statements use pattern matching conditions (->) which can be customized by overriding the equals() method in the related class.
  4. Execution flow: switch statements execute the first matching case and execute all subsequent cases unless a break statement is encountered. when statements execute the block associated with the first matching condition and terminate the execution without executing any further condition checks.
  5. Additional features: switch statements can use the default keyword to specify a default case if none of the cases match. when statements can use the else keyword to specify a default value or behavior if none of the conditions match.

Overall, switch statements are more traditional and suitable for basic cases with a limited set of conditions. On the other hand, when statements are more flexible and powerful, especially when working with complex types and custom matching conditions. Note that when statements were introduced in Java 12 as part of the Java feature preview.