Control Flow in Kotlin: When Expression

1. Why Use When?

The when expression in Kotlin is a powerful alternative to the traditional if-else-if ladder. It is used to:

2. How to Use When? (With Example)

The when expression evaluates a value or condition and executes the corresponding block.

fun main() {
    val day = 3
    val dayName = when(day) {
        1 -> "Monday"
        2 -> "Tuesday"
        3 -> "Wednesday"
        4 -> "Thursday"
        5 -> "Friday"
        6 -> "Saturday"
        7 -> "Sunday"
        else -> "Invalid day"
    }
    println("Day: $dayName")
}

Output:

Day: Wednesday

3. Explain Each Form

3.1 Basic When

Matches a value against constants:

val color = "Red"
when (color) {
    "Red" -> println("Stop")
    "Green" -> println("Go")
    "Yellow" -> println("Caution")
    else -> println("Unknown color")
}

3.2 When with Multiple Conditions

You can group multiple conditions with commas:

val number = 3
when (number) {
    1, 3, 5, 7, 9 -> println("Odd number")
    2, 4, 6, 8, 10 -> println("Even number")
    else -> println("Out of range")
}

3.3 When as an Expression

When can return a value:

val score = 85
val grade = when {
    score >= 90 -> "A"
    score >= 75 -> "B"
    score >= 60 -> "C"
    else -> "Fail"
}
println("Grade: $grade")

3.4 When with Ranges and Types

You can check for ranges or types:

val x: Any = 42
when (x) {
    in 1..50 -> println("x is between 1 and 50")
    is String -> println("x is a string")
    else -> println("Unknown type or value")
}

4. Key Points

5. Interview Questions

Why Use When?

How When Works?

Other Common Questions