How to Use the 'When' Expression In Kotlin?

11 minutes read

The "when" expression in Kotlin is used as a replacement for the switch statement in other programming languages. It allows you to define multiple branches of code and execute the branch that matches a given condition.


Here is the syntax of the "when" expression:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
when (variable) {
    value1 -> {
        // Code to execute when variable equals value1
    }
    value2 -> {
        // Code to execute when variable equals value2
    }
    else -> {
        // Code to execute when none of the above conditions are met
    }
}


The "variable" in the when expression is the value that you want to match against. You can provide multiple values separated by commas if you want to execute the same code for different values.


Each branch is introduced with the value followed by an arrow (->). Inside the branch, you write the code that should be executed when the corresponding condition is met.


If none of the conditions match the given variable, the "else" branch (optional) is executed. It acts as a default branch that covers any other possible values.


The "when" expression can also be used without an argument. In this case, you provide conditions directly inside the branches. For example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
when {
    condition1 -> {
        // Code to execute when condition1 is true
    }
    condition2 -> {
        // Code to execute when condition2 is true
    }
    else -> {
        // Code to execute when none of the above conditions are true
    }
}


Using the "when" expression, you can simplify complex if-else chains and make your code more concise and readable.

Best Kotlin Books to Read in 2024

1
Atomic Kotlin

Rating is 5 out of 5

Atomic Kotlin

2
Head First Android Development: A Learner's Guide to Building Android Apps with Kotlin

Rating is 4.9 out of 5

Head First Android Development: A Learner's Guide to Building Android Apps with Kotlin

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

Rating is 4.8 out of 5

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

4
Kotlin in Action

Rating is 4.7 out of 5

Kotlin in Action

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

Rating is 4.6 out of 5

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

6
Head First Kotlin: A Brain-Friendly Guide

Rating is 4.5 out of 5

Head First Kotlin: A Brain-Friendly Guide

7
Kotlin Cookbook: A Problem-Focused Approach

Rating is 4.4 out of 5

Kotlin Cookbook: A Problem-Focused Approach

8
How to Build Android Apps with Kotlin: A practical guide to developing, testing, and publishing your first Android apps, 2nd Edition

Rating is 4.3 out of 5

How to Build Android Apps with Kotlin: A practical guide to developing, testing, and publishing your first Android apps, 2nd Edition

9
Modern Android 13 Development Cookbook: Over 70 recipes to solve Android development issues and create better apps with Kotlin and Jetpack Compose

Rating is 4.2 out of 5

Modern Android 13 Development Cookbook: Over 70 recipes to solve Android development issues and create better apps with Kotlin and Jetpack Compose

10
Java to Kotlin: A Refactoring Guidebook

Rating is 4.1 out of 5

Java to Kotlin: A Refactoring Guidebook


How to use 'when' with type-checking in Kotlin?

In Kotlin, you can use the when expression with type-checking to check the type of an object and perform specific actions based on the type.


The syntax for using when with type-checking is as follows:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
when (objectToCheck) {
    is TypeOne -> {
        // Action to perform if objectToCheck is of TypeOne
    }
    is TypeTwo -> {
        // Action to perform if objectToCheck is of TypeTwo
    }
    else -> {
        // Action to perform if objectToCheck does not match any types
    }
}


Here's an example to illustrate how to use when with type-checking:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
fun processData(data: Any) {
    when (data) {
        is String -> {
            println("String: $data")
        }
        is Int -> {
            println("Integer: $data")
        }
        is Boolean -> {
            println("Boolean: $data")
        }
        else -> {
            println("Unknown type: $data")
        }
    }
}

fun main() {
    processData("Hello")     // Output: String: Hello
    processData(42)          // Output: Integer: 42
    processData(true)        // Output: Boolean: true
    processData(3.14)        // Output: Unknown type: 3.14
}


In this example, when the processData function is called with different types of data, the when expression checks the type of the data parameter and executes the corresponding block of code based on the type.


Note that the else branch is optional, and it will be executed if none of the other branches match.


How to use the 'when' expression in Kotlin?

The when expression in Kotlin is a more powerful alternative to the traditional switch statement in other programming languages. It allows you to branch your code based on multiple conditions.


Here's how you can use the when expression in Kotlin:

  1. Basic usage:
1
2
3
4
5
6
7
8
9
val x = 5

when (x) {
    1 -> println("x is 1")
    2 -> println("x is 2")
    3, 4 -> println("x is either 3 or 4")
    in 5..10 -> println("x is between 5 and 10 (inclusive)")
    else -> println("x is unknown")
}


In this example, the when expression checks the value of x and executes the branch whose condition matches.

  1. Checking type:
1
2
3
4
5
6
7
val obj: Any = "Hello"

when (obj) {
    is String -> println("obj is a String")
    is Int -> println("obj is an Int")
    else -> println("obj is something else")
}


The when expression can also check the type of an object.

  1. Using when as an expression:
1
2
3
4
5
6
7
val result = when (x) {
    1 -> "x is 1"
    2 -> "x is 2"
    else -> "x is unknown"
}

println(result)


You can assign the result of the when expression to a variable, which allows you to use it in further calculations or print it.


These are just a few examples of how to use the when expression in Kotlin. It provides many more possibilities, such as using ranges, combining conditions, and more.


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

In Kotlin, sealed classes are used to represent restricted class hierarchies, where all subclasses must be defined within the same file. The when expression is often used with sealed classes to handle different cases based on the type of the sealed class instance.


Here's an example of how to use when with sealed classes in Kotlin:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
sealed class Result
data class Success(val value: Int) : Result()
data class Error(val message: String) : Result()
object Loading : Result()

fun processResult(result: Result) {
    when (result) {
        is Success -> {
            println("Success: ${result.value}")
        }
        is Error -> {
            println("Error: ${result.message}")
        }
        Loading -> {
            println("Loading...")
        }
    }
}

fun main() {
    val result1 = Success(10)
    processResult(result1)

    val result2 = Error("Something went wrong")
    processResult(result2)

    processResult(Loading)
}


In this example, the sealed class Result has three subclasses: Success, Error, and Loading. The when expression in the processResult function is used to handle different cases based on the type of result.


When result is of type Success, it prints the value of the success. When result is of type Error, it prints the error message. And when result is of type Loading, it prints "Loading...".


In the main function, we create different instances of the Result subclasses and pass them to the processResult function to see how they are handled by the when expression.


By using when with sealed classes, you can easily handle different cases based on the type of the sealed class instance, ensuring that all possible cases are covered.


What is the return type of a 'when' expression in Kotlin when used as an expression?

The return type of a when expression in Kotlin, when used as an expression, is the common supertype of all its branch conditions.


If the branch conditions have no common supertype, the return type of the when expression will be Any?, which is the top-level supertype in Kotlin.


However, if the branch conditions have a common supertype, that will be the return type of the when expression.

Facebook Twitter LinkedIn Whatsapp Pocket

Related Posts:

To initialize an array of buttons in Kotlin, you can follow these steps:Declare an array variable of type Button and specify the desired size of the array.Use the Array constructor and pass the size of the array as the first argument.Inside the constructor, us...
In Kotlin, you can suppress check-style warnings by using the @Suppress annotation. This annotation is used to suppress specific warnings at the statement or expression level.To suppress a check-style warning, you need to follow these steps:Identify the specif...
In Haskell, there are several ways to check the type of a value or expression. Here are a few methods commonly used:Type Inference: Haskell has a powerful type inference system that can automatically deduce the type of an expression. Therefore, you don't a...