How to Use the 'When' Expression In Kotlin?

11 minutes read

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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
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.

Best Kotlin Books to Read in 2024

1
Atomic Kotlin

Rating is 5 out of 5

Atomic Kotlin

2
Kotlin Cookbook: A Problem-Focused Approach

Rating is 4.9 out of 5

Kotlin Cookbook: A Problem-Focused Approach

3
Head First Kotlin: A Brain-Friendly Guide

Rating is 4.8 out of 5

Head First Kotlin: A Brain-Friendly Guide

4
Kotlin in Action

Rating is 4.7 out of 5

Kotlin in Action

5
Kotlin In-Depth: A Guide to a Multipurpose Programming Language for Server-Side, Front-End, Android, and Multiplatform Mobile (English Edition)

Rating is 4.6 out of 5

Kotlin In-Depth: A Guide to a Multipurpose Programming Language for Server-Side, Front-End, Android, and Multiplatform Mobile (English Edition)

6
Kotlin Design Patterns and Best Practices: Build scalable applications using traditional, reactive, and concurrent design patterns in Kotlin, 2nd Edition

Rating is 4.5 out of 5

Kotlin Design Patterns and Best Practices: Build scalable applications using traditional, reactive, and concurrent design patterns in Kotlin, 2nd Edition

7
Kotlin Programming: The Big Nerd Ranch Guide (Big Nerd Ranch Guides)

Rating is 4.4 out of 5

Kotlin Programming: The Big Nerd Ranch Guide (Big Nerd Ranch Guides)

8
Java to Kotlin

Rating is 4.2 out of 5

Java to Kotlin

9
Kotlin Essentials (Kotlin for Developers)

Rating is 4.1 out of 5

Kotlin Essentials (Kotlin for Developers)


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.
1
sealed class Result


  1. Create subclasses of the sealed class using the object or data keyword.
1
2
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.
1
2
3
4
5
6
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:
1
2
3
4
5
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:
1
2
3
4
5
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:
1
2
3
4
5
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:
1
2
3
4
5
6
7
8
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.

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

Related Posts:

To use a Kotlin function in Java, you can follow these steps:Create a Kotlin function that you want to use in Java. For example, let's consider a simple function named printMessage() that prints a message. fun printMessage() { println("Hello, world...
Working with Android extensions in Kotlin allows you to leverage the power of Kotlin's extension functions to easily enhance the functionality of Android classes. Here's how you can work with Android extensions in Kotlin.To create an Android extension,...
To run Kotlin on Ubuntu, you can follow these steps:Install Java Development Kit (JDK): Since Kotlin runs on the Java Virtual Machine (JVM), you need to have Java installed on your system. Open a terminal and run the following command to install the default JD...
To create a traditional for-loop in Kotlin, you can use the for keyword followed by a pair of parentheses enclosing an initialization expression, a condition expression, and an iteration expression. Inside the loop body, you can perform the desired operations.
In Kotlin, the 'with' expression is used to simplify the code when working with an object. It allows you to call multiple methods or access properties of the object without repeating its name.The basic syntax of the 'with' expression is: with(o...
The Kotlin Standard Library functions are a collection of commonly used extension functions and top-level functions provided by the Kotlin programming language. These functions aim to simplify and enhance the development process by offering a set of utility fu...