What if you could replace many confusing checks with one simple, clear expression?
Why When with multiple conditions in Kotlin? - Purpose & Use Cases
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.
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 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.
if (fruit == "apple" || fruit == "pear") { println("This is a sweet fruit") } else if (fruit == "lemon" || fruit == "lime") { println("This is a sour fruit") }
when (fruit) {
"apple", "pear" -> println("This is a sweet fruit")
"lemon", "lime" -> println("This is a sour fruit")
}You can write clear and concise code that handles many conditions together, making your programs easier to read and maintain.
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.
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.