What if you could replace messy if-else chains with a simple, readable list of conditions?
Why When without argument in Kotlin? - Purpose & Use Cases
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.
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 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.
if (x > 0) { println("Positive") } else if (x == 0) { println("Zero") } else { println("Negative") }
when {
x > 0 -> println("Positive")
x == 0 -> println("Zero")
else -> println("Negative")
}You can write clear, neat code that checks many different conditions without repeating yourself or getting lost in nested ifs.
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.
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.