0
0
Kotlinprogramming~5 mins

When with multiple conditions in Kotlin

Choose your learning style9 modes available
Introduction

The when expression helps you choose what to do based on different values. Using multiple conditions lets you check several options together in one place.

You want to run the same code for several possible values.
You have a variable that can be one of many things and want to handle groups of them similarly.
You want to keep your code clean by combining cases instead of writing many separate checks.
Syntax
Kotlin
when (variable) {
    value1, value2, value3 -> {
        // code for these values
    }
    value4 -> {
        // code for value4
    }
    else -> {
        // code if no match
    }
}

You separate multiple conditions with commas.

The else block runs if no other condition matches.

Examples
This checks if color is either "red" or "blue" and prints "Primary color" for both.
Kotlin
val color = "red"
when (color) {
    "red", "blue" -> println("Primary color")
    "green" -> println("Secondary color")
    else -> println("Unknown color")
}
This groups 6 and 7 as weekend days and 1 to 5 as weekdays.
Kotlin
val day = 6
when (day) {
    6, 7 -> println("Weekend")
    in 1..5 -> println("Weekday")
    else -> println("Invalid day")
}
Sample Program

This program checks the fruit name and prints a message based on groups of fruits.

Kotlin
fun main() {
    val fruit = "apple"
    when (fruit) {
        "apple", "banana", "orange" -> println("This is a common fruit.")
        "kiwi", "mango" -> println("This is a tropical fruit.")
        else -> println("Unknown fruit")
    }
}
OutputSuccess
Important Notes

You can combine as many values as you want separated by commas.

Using when with multiple conditions keeps your code shorter and easier to read.

Summary

when lets you check many values in one place.

Multiple conditions are separated by commas.

Use else to handle any unmatched cases.