0
0
Kotlinprogramming~3 mins

Why When with multiple conditions in Kotlin? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could replace many confusing checks with one simple, clear expression?

The Scenario

Imagine you have a list of fruits and you want to print a special message for each type. You try to check each fruit one by one using many if-else statements.

The Problem

Using many if-else statements makes your code long, hard to read, and easy to make mistakes. It's like checking every fruit separately instead of grouping similar ones together.

The Solution

The when expression lets you check multiple conditions in a clean and organized way. You can group several cases together, making your code shorter and easier to understand.

Before vs After
Before
if (fruit == "apple" || fruit == "pear") {
    println("This is a sweet fruit")
} else if (fruit == "lemon" || fruit == "lime") {
    println("This is a sour fruit")
}
After
when (fruit) {
    "apple", "pear" -> println("This is a sweet fruit")
    "lemon", "lime" -> println("This is a sour fruit")
}
What It Enables

You can write clear and concise code that handles many conditions together, making your programs easier to read and maintain.

Real Life Example

Think about a traffic light system where you want to perform the same action for both red and yellow lights (stop), and a different action for green (go). Using when with multiple conditions groups these actions neatly.

Key Takeaways

Manual checks with many if-else are long and confusing.

when groups multiple conditions for cleaner code.

This makes your programs easier to read and less error-prone.