0
0
Kotlinprogramming~3 mins

Why When with ranges and types in Kotlin? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could replace messy if-else chains with one simple, powerful expression?

The Scenario

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.

The Problem

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 Solution

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.

Before vs After
Before
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")
}
After
when {
    x in 1..10 -> println("Small number")
    x in 11..100 -> println("Medium number")
    obj is String -> println("It's a string")
}
What It Enables

You can write clean, readable code that handles many conditions on values and types without clutter.

Real Life Example

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.

Key Takeaways

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.