Kotlin When Expression

Kotlin , when replaces the switch operator of C-like languages. Kotlin, when expression works as a switch statement of other language (Java, C++, C).


In the simplest form it looks like this

Let's see a simple example of when expression.


fun main(array: Array<String>) {

    var x: Int = 2

    when (x) {
        1 -> println("one")
        2 -> println("Two")
        3 -> println("Three")
        else -> {
            println("Other statement..")
        }
    }
}
Two

When matches its argument against all branches sequentially until some branch condition is satisfied. If no branch match then it execute else branch.

Using when as an Expression


fun main(array: Array<String>) {

    var x: Int = 2

    var result: String = when (x) {
        1 -> "One"
        2 -> "Two"
        3 -> "Three"
        else -> {
            println("Other statement..")
            "else"
        }
    }

    println(result)
}
Two

Using when in the range

The when expression also check the ranges of input provided in when condition. A range is created using .. (double dot) operator. The in operator is used to check if a value belongs to a range.


fun main(array: Array<String>) {

    var x: Int = 2

    var result: String = when (x) {
        in 1..5 -> {
            "1...5"
        }
        in 6..12 -> {
            "6...12"
        }
        else -> {
            "else block.."
        }
    }

    println(result)
}
1...5
woman avatar