How to Use the "When" Expression In Kotlin?

13 minutes read

In Kotlin, the "when" expression is a versatile construct that allows you to replace the switch statement from other programming languages. It allows you to check multiple conditions and execute different blocks of code based on the matched condition.


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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
when (variableName) {
    value1 -> {
        // Code block to be executed when variableName matches value1
    }
    value2 -> {
        // Code block to be executed when variableName matches value2
    }
    value3, value4 -> {
        // Code block to be executed when variableName matches either value3 or value4
    }
    // ...
    else -> {
        // Code block to be executed when none of the above conditions are met
    }
}


Here's an explanation of each component:

  • variableName represents the variable on which the conditions are checked.
  • value1, value2, value3, etc. are the possible values that variableName can take.
  • Each value is followed by an arrow ->, which designates the code block to be executed when the respective value matches variableName.
  • You can combine multiple values using commas if they should execute the same code block.
  • The else keyword represents a default condition when none of the specified values match variableName.


The "when" expression supports various data types as the target for the conditions, including literals, variables, enum constants, and even expressions.


Additionally, the "when" expression also supports more complex conditions using "is" and "in" keywords. You can use "is" to perform type checks, and "in" to check whether a value is within a range or collection.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
when (x) {
    is String -> {
        // Code block to be executed when x is of type String
    }
    in 1..10 -> {
        // Code block to be executed when x is within the range 1 to 10
    }
    else -> {
        // Code block to be executed when none of the above conditions are met
    }
}


The "when" expression provides a concise and readable way to handle multiple branches of code based on different conditions in Kotlin.

Best Kotlin Books to Read of July 2024

1
Atomic Kotlin

Rating is 5 out of 5

Atomic Kotlin

2
Kotlin in Action

Rating is 4.9 out of 5

Kotlin in Action

3
Kotlin Cookbook: A Problem-Focused Approach

Rating is 4.8 out of 5

Kotlin Cookbook: A Problem-Focused Approach

4
Head First Kotlin: A Brain-Friendly Guide

Rating is 4.7 out of 5

Head First Kotlin: A Brain-Friendly Guide

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

Rating is 4.6 out of 5

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

6
Effective Kotlin: Best Practices (Kotlin for Developers Book 5)

Rating is 4.5 out of 5

Effective Kotlin: Best Practices (Kotlin for Developers Book 5)

7
Java to Kotlin: A Refactoring Guidebook

Rating is 4.4 out of 5

Java to Kotlin: A Refactoring Guidebook

8
Learn to Program with Kotlin: From the Basics to Projects with Text and Image Processing

Rating is 4.3 out of 5

Learn to Program with Kotlin: From the Basics to Projects with Text and Image Processing


How to use the "when" expression with nullable values in Kotlin?

To use the "when" expression with nullable values in Kotlin, you can use a combination of null checks and smart casts. Here's an example:

1
2
3
4
5
6
fun printLength(str: String?) {
    when (str) {
        null -> println("String is null")
        else -> println("Length of string is ${str.length}")
    }
}


In this example, the str parameter is nullable. Inside the when expression, you can handle the null case by using the null keyword. If the value is null, the code block under null will be executed. If the value is not null, you can safely access its properties or call its methods.


You can also use the is keyword to perform type checks:

1
2
3
4
5
6
7
8
fun printLength(str: Any?) {
    when (str) {
        null -> println("Object is null")
        is String -> println("Length of string is ${str.length}")
        is Int -> println("Int value is $str")
        else -> println("Unknown object type")
    }
}


In this example, the str parameter is of type Any?, which means it can hold any nullable value. The is keyword is used to check the type of the value, and the appropriate code block is executed based on the type.


By performing null checks and smart casts, you can safely use the "when" expression with nullable values in Kotlin.


How to use the "when" expression to check for types in Kotlin?

In Kotlin, the when expression can be used to check for types. It allows you to perform different actions based on the type of an object. Here's how you can use the when expression to check for types:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
fun checkType(value: Any) {
    when (value) {
        is String -> println("String: $value")
        is Int -> println("Int: $value")
        is Double -> println("Double: $value")
        else -> println("Unknown type")
    }
}

fun main() {
    checkType("Hello")       // Output: String: Hello
    checkType(42)            // Output: Int: 42
    checkType(3.14)          // Output: Double: 3.14
    checkType(true)          // Output: Unknown type
}


In the checkType function, the when expression is used to check the type of the value parameter. If the value is a String, it prints "String: $value". If it's an Int, it prints "Int: $value". If it's a Double, it prints "Double: $value". Otherwise, if it doesn't match any of the specified types, it prints "Unknown type".


You can add as many type checks as necessary in the when expression by using is followed by the type. Note that the order of the type checks matters, as the first matching condition will be executed.


What are some alternative approaches to using the "when" expression in Kotlin?

In Kotlin, the "when" expression is a powerful feature that allows developers to write concise and readable code for conditional branching. However, there are a few alternative approaches that can be used in certain scenarios. Some of these approaches include:

  1. If-else statements: Instead of using "when" expression, you can use traditional if-else statements for conditional branching. This approach is useful when you have a small number of conditions, and using "when" expression might make the code less readable.


Example:

1
2
3
4
5
6
7
if (value == 1) {
    // do something
} else if (value == 2) {
    // do something else
} else {
    // do something if none of the conditions match
}


  1. Map-based approach: If you have a large number of conditions and the logic within each condition is complex, you can use a map-based approach. In this approach, you store the conditions as keys in a map and associate them with corresponding actions or functions.


Example:

1
2
3
4
5
6
7
8
9
val actions = mapOf<Int, () -> Unit>(
    1 to { // do something },
    2 to { // do something else },
    3 to { // do another thing },
    // and so on...
)

val selectedAction = actions[value]
selectedAction?.invoke()


  1. Object-oriented approach: Instead of using "when" expression, you can take advantage of object-oriented principles like inheritance and polymorphism to achieve conditional branching. This approach allows you to define different classes or interfaces for each condition and let the objects themselves handle the branching.


Example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
interface Action {
    fun execute()
}

class Action1 : Action {
    override fun execute() { // do something }
}

class Action2 : Action {
    override fun execute() { // do something else }
}

fun executeAction(value: Int) {
    val action: Action = when (value) {
        1 -> Action1()
        2 -> Action2()
        else -> throw IllegalArgumentException("Invalid value")
    }
    action.execute()
}


These alternative approaches can be useful depending on the complexity and readability requirements of your code. However, when used appropriately, the "when" expression remains a powerful and expressive solution for conditional branching in Kotlin.


What is the recommended approach for using the "when" expression in Kotlin?

The "when" expression in Kotlin is a powerful alternative to traditional switch statements. It is recommended to use the "when" expression in the following approach:

  1. Use "when" as an expression: In Kotlin, "when" can be used both as a statement and as an expression. Using it as an expression allows you to assign the result of "when" to a variable or use it in a return statement.
  2. Match multiple conditions: "when" can be used to match multiple conditions in a concise manner. You can provide multiple conditions separated by commas and execute the code block associated with the first matching condition.
  3. Use "else" as a fallback: The "else" keyword in a "when" expression is similar to the default case in switch statements. It is executed when none of the conditions match. It is recommended to include an "else" block to handle unexpected cases.
  4. Check against specific values: You can use "when" to check against specific values, ranges, or even custom conditions. For example, you can match against string values, numbers, boolean values, or even check if a value is within a certain range.
  5. Combine conditions using "is" and "in": By using the "is" keyword, you can check if an object is of a specific type. You can also use the "in" keyword to check if a value is present in a range, collection, or array.
  6. Use "when" inside functions or expressions: "when" can be used in any part of a Kotlin program, including functions, constructors, and even return statements. This flexibility allows you to use "when" wherever you need to make decisions based on different conditions.


Overall, the recommended approach for using the "when" expression in Kotlin is to leverage its expressive power by matching multiple conditions, using the "else" block as a fallback, and combining conditions using "is" and "in".


How to use the "when" expression with integer values in Kotlin?

In Kotlin, the "when" expression can be used with integer values by specifying the integer conditions in the different branches. Here's an example of how to use the "when" expression with integer values in Kotlin:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
fun main() {
    val number = 5

    val result = when (number) {
        1 -> "One"
        2 -> "Two"
        3, 4 -> "Three or Four" // Multiple values in a single branch
        in 5..10 -> "Five to Ten" // Range condition
        else -> "Other" // Default case
    }

    println("Result: $result")
}


In the above code, we have a variable number initialized with the value 5. The when expression checks the different conditions and returns a corresponding result.

  • If number is 1, it returns "One".
  • If number is 2, it returns "Two".
  • If number is 3 or 4, it returns "Three or Four".
  • If number is between 5 and 10 (inclusive), it returns "Five to Ten".
  • For any other value of number, it returns "Other" (default case).


In this way, you can use the "when" expression with integer values in Kotlin.


What is the purpose of the "when" expression in Kotlin?

The "when" expression in Kotlin is used for conditional checking and branching. It is similar to the "switch" statement in other programming languages, but more flexible and powerful.


The main purpose of the "when" expression is to simplify complex if-else chains by providing a concise and readable way to check multiple conditions. It allows you to evaluate an expression and then match its value against different cases.


The "when" expression can check for various types of conditions, including constant values, ranges, type checks, and even custom conditions. It can have multiple branches with different conditions, and it guarantees that only one branch will be executed. If none of the conditions match, you can provide a default branch.


In summary, the purpose of the "when" expression in Kotlin is to provide a more versatile and expressive way of handling conditional logic and branching in your code.

Twitter LinkedIn Telegram Whatsapp

Related Posts:

The &#34;with&#34; expression in Kotlin provides a concise way to perform a series of operations on an object without having to repeatedly call its methods or properties. It simplifies code by allowing you to temporarily change the working context to the objec...
To create a Kotlin UInt from Java, you can use the following code snippets:In Java: import kotlin.jvm.JvmField; public class JavaClass { @JvmField public static int createUInt() { return 10; } } In Kotlin: val uintValue = JavaClass.createU...
Working with the Kotlin Collections API allows you to efficiently manage and manipulate collections of data in your Kotlin code. Kotlin provides a rich set of built-in functions and operators that make it easy to perform common operations on lists, sets, and m...