What if you could replace long, confusing if-else chains with a simple, elegant expression that does it all?
Why When expression as powerful switch in Kotlin? - Purpose & Use Cases
Imagine you have a list of tasks, and you want to perform different actions based on the type of each task. Doing this manually means writing many if-else statements, checking each condition one by one.
Using many if-else statements is slow to write and hard to read. It's easy to make mistakes, like missing a case or repeating code. When you want to add new cases, you have to change many places, which can cause bugs.
The when expression in Kotlin acts like a powerful switch. It lets you check many conditions clearly and concisely in one place. It's easier to read, less error-prone, and you can return values directly from it.
if (x == 1) { println("One") } else if (x == 2) { println("Two") } else { println("Other") }
when (x) {
1 -> println("One")
2 -> println("Two")
else -> println("Other")
}It enables writing clear, concise, and maintainable code that handles many conditions elegantly in one place.
Think of a vending machine that gives different snacks based on the button pressed. Using when, you can easily map buttons to snacks without messy if-else chains.
Manual if-else chains are hard to read and maintain.
When expression simplifies multiple condition checks.
It makes your code cleaner, safer, and easier to update.