kotlin
  1. kotlin-when-expression

Kotlin when Expression

In Kotlin, the when expression is a powerful control flow tool that helps to write efficient and concise code. It is used as an alternative to the traditional if-else statements and can also be used to replace switch-case statements found in other programming languages.

Syntax

The basic syntax of the when expression is as follows:

when (variableName) {
    value1 -> {
        // Code to be executed when variableName is equal to value1
    }
    value2 -> {
        // Code to be executed when variableName is equal to value2
    }
    else -> {
        // Code to be executed when none of the above cases match
    }
}

Example

Here's an example of how the when expression works in Kotlin:

fun main() {
    val number = 2
    when (number) {
        1 -> println("One")
        2 -> println("Two")
        3 -> println("Three")
        else -> println("Unknown Number")
    }
}

Output

The output of the above Kotlin code will be:

Two

Explanation

The above Kotlin code declares a number variable and assigns it the value of 2. The when expression is then used to check the value of number. If number is equal to 1, the println statement will print One. Similarly, if number is equal to 2, the println statement will print Two. If number is equal to 3, the println statement will print Three. Finally, if number is not equal to any of the above cases, the else block will be executed, which prints Unknown Number to the console.

Use

The when expression is commonly used in the following scenarios:

  • To replace traditional if-else statements
  • To replace switch-case statements found in other programming languages
  • To check the type of an object

Important Points

Here are some important points to keep in mind when using the when expression in Kotlin:

  • The when expression is used to compare a value against multiple possible values.
  • The else block is optional and will be executed if none of the other cases match.
  • The when expression can also be used to check the type of an object.

Summary

In summary, the when expression is a powerful control flow tool in Kotlin that is used as an alternative to the traditional if-else and switch-case statements found in other programming languages. It allows developers to write efficient and concise code, making it a useful feature to learn and use in Kotlin programming.

Published on: