0
0
Kotlinprogramming~3 mins

Why When without argument in Kotlin? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could replace messy if-else chains with a simple, readable list of conditions?

The Scenario

Imagine you have many different conditions to check, like deciding what to do based on the weather. You write many if-else statements, each checking a different condition one by one.

The Problem

This manual way is slow to write and hard to read. It's easy to make mistakes, like forgetting a condition or mixing up the order. It also makes your code long and confusing.

The Solution

The when expression without an argument lets you check multiple conditions clearly and simply. It works like a clean list of rules, making your code easier to read and less error-prone.

Before vs After
Before
if (x > 0) {
    println("Positive")
} else if (x == 0) {
    println("Zero")
} else {
    println("Negative")
}
After
when {
    x > 0 -> println("Positive")
    x == 0 -> println("Zero")
    else -> println("Negative")
}
What It Enables

You can write clear, neat code that checks many different conditions without repeating yourself or getting lost in nested ifs.

Real Life Example

For example, deciding what message to show a user based on their age, membership status, and activity level all in one place, without complicated if-else chains.

Key Takeaways

When without argument lets you check many conditions clearly.

It makes your code shorter and easier to understand.

It helps avoid mistakes common in long if-else chains.