What if you could replace messy if-else chains with one simple, powerful expression?
Why When with ranges and types in Kotlin? - Purpose & Use Cases
Imagine you have to check many different conditions on a number or an object type one by one using many if-else statements.
For example, checking if a number falls into certain ranges or if an object is of a certain type.
Writing many if-else statements is slow and confusing.
It's easy to make mistakes, miss a condition, or write repetitive code.
It becomes hard to read and maintain as the number of conditions grows.
The when expression in Kotlin lets you check multiple conditions clearly and concisely.
You can check ranges and types in one place, making your code easier to read and less error-prone.
if (x in 1..10) { println("Small number") } else if (x in 11..100) { println("Medium number") } else if (obj is String) { println("It's a string") }
when {
x in 1..10 -> println("Small number")
x in 11..100 -> println("Medium number")
obj is String -> println("It's a string")
}You can write clean, readable code that handles many conditions on values and types without clutter.
Checking user input: if a number is in a valid range or if the input is a specific type like String or Int, all in one simple structure.
Manual if-else chains are hard to read and error-prone.
when handles ranges and types clearly in one place.
It makes your code simpler, cleaner, and easier to maintain.