0
0
Kotlinprogramming~3 mins

Why When expression as powerful switch in Kotlin? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could replace long, confusing if-else chains with a simple, elegant expression that does it all?

The Scenario

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.

The Problem

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 Solution

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.

Before vs After
Before
if (x == 1) {
  println("One")
} else if (x == 2) {
  println("Two")
} else {
  println("Other")
}
After
when (x) {
  1 -> println("One")
  2 -> println("Two")
  else -> println("Other")
}
What It Enables

It enables writing clear, concise, and maintainable code that handles many conditions elegantly in one place.

Real Life Example

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.

Key Takeaways

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.