When in Kotlin

In Kotlin, when is a control flow statement that provides a more concise alternative to the traditional switch statement found in other programming languages. The when statement allows you to match a value against a series of possible patterns, and execute the corresponding code block for the first pattern that matches.

The general syntax of a when statement is:

when (value) {
    pattern1 -> {
        // code to be executed when value matches pattern1
    }
    pattern2 -> {
        // code to be executed when value matches pattern2
    }
    // more patterns and code blocks
    else -> {
        // code to be executed if no patterns match
    }
}

In this syntax, value is the value to be matched against the patterns. Each pattern is specified using the -> symbol, and is followed by a code block to be executed if the pattern matches. If no patterns match, the else block is executed.

Here’s an example of a when statement that matches an integer value:

val x = 5
when (x) {
    1 -> println("One")
    2 -> println("Two")
    3, 4 -> println("Three or Four")
    in 5..10 -> println("Between Five and Ten")
    else -> println("Not a valid number")
}

In this example, the value of x is matched against several patterns. If x is 1, the string “One” is printed. If x is 2, the string “Two” is printed. If x is 3 or 4, the string “Three or Four” is printed. If x is between 5 and 10 (inclusive), the string “Between Five and Ten” is printed. If x doesn’t match any of the patterns, the string “Not a valid number” is printed.

The when statement can also be used without an argument, in which case it serves as a more flexible alternative to an if-else statement:

val y = 10
when {
    y < 0 -> println("Negative")
    y == 0 -> println("Zero")
    y > 0 -> println("Positive")
}

In this example, the code block executed depends on the conditions specified in the patterns, rather than on a specific value of y.