0
0
Kotlinprogramming~5 mins

When expression as powerful switch in Kotlin

Choose your learning style9 modes available
Introduction

The when expression helps you choose what to do based on different values, like a smart traffic controller.

You want to run different code depending on a variable's value.
You need to check multiple conditions without writing many <code>if</code> statements.
You want to replace a long <code>if-else</code> chain with cleaner code.
You want to handle different types or ranges of values easily.
Syntax
Kotlin
when (variable) {
    value1 -> action1
    value2 -> action2
    in range -> action3
    else -> defaultAction
}

The when expression checks the variable against each case.

The else branch is like a default catch-all if no other case matches.

Examples
Prints "Two" because x is 2.
Kotlin
val x = 2
when (x) {
    1 -> println("One")
    2 -> println("Two")
    else -> println("Other")
}
Prints "Between 5 and 10" because y is 5.
Kotlin
val y = 5
when (y) {
    in 1..4 -> println("Between 1 and 4")
    in 5..10 -> println("Between 5 and 10")
    else -> println("Out of range")
}
Checks the type of obj and prints "It's a string".
Kotlin
val obj: Any = "Hello"
when (obj) {
    is String -> println("It's a string")
    is Int -> println("It's an integer")
    else -> println("Unknown type")
}
Sample Program

This program assigns a letter grade based on the numeric score using when. It prints the score and the grade.

Kotlin
fun main() {
    val score = 85
    val grade = when (score) {
        in 90..100 -> "A"
        in 80..89 -> "B"
        in 70..79 -> "C"
        in 60..69 -> "D"
        else -> "F"
    }
    println("Score: $score, Grade: $grade")
}
OutputSuccess
Important Notes

You can use when without an argument to check complex conditions.

Each branch can have multiple statements if you use curly braces.

Summary

when is a cleaner way to choose actions based on values.

It works like a switch but is more powerful and flexible.

Use else to handle unexpected cases.