🧭 Kotlin – When Expression: The Modern Switch Statement
🧲 Introduction – Why Learn Kotlin when Expression?
The traditional switch statement in Java is limited and verbose. Kotlin replaces it with the much more powerful and flexible when expression. It allows pattern matching, range checks, type checking, and value returns—all in a clean, readable way.
🎯 In this guide, you’ll learn:
- How to use whenas a switch alternative
- Match values, ranges, and conditions
- Return values from whenexpressions
- Handle type checks with smart casting
🔀 What Is a when Expression in Kotlin?
The when expression checks a value against multiple conditions and executes the matching block. It’s Kotlin’s answer to the Java switch.
✅ Basic Syntax:
val day = 3
when (day) {
    1 -> println("Monday")
    2 -> println("Tuesday")
    3 -> println("Wednesday")
    else -> println("Invalid day")
}
🟢 Output:
Wednesday
🔁 when as an Expression (Return Value)
You can assign the result of a when to a variable:
val number = 2
val result = when (number) {
    1 -> "One"
    2 -> "Two"
    3 -> "Three"
    else -> "Unknown"
}
println(result)
🟢 Output:
Two
🔢 Matching Multiple Values in a Case
val letter = 'A'
when (letter) {
    'A', 'E', 'I', 'O', 'U' -> println("Vowel")
    else -> println("Consonant")
}
🟢 Output:
Vowel
🧮 Using Ranges and Collections
val age = 25
when (age) {
    in 0..12 -> println("Child")
    in 13..19 -> println("Teenager")
    in 20..59 -> println("Adult")
    else -> println("Senior")
}
✅ Use in keyword to check if a value lies within a range.
🔍 Type Checking in when
You can use is to perform type checks and automatically smart-cast.
fun checkType(x: Any) {
    when (x) {
        is Int -> println("Integer: ${x + 1}")
        is String -> println("String of length ${x.length}")
        else -> println("Unknown type")
    }
}
🟢 Output:
String of length 6 // if you pass "Kotlin"
⚠️ When Without Argument (Condition-Based)
You can omit the input and write conditions directly:
val score = 85
when {
    score >= 90 -> println("A Grade")
    score >= 75 -> println("B Grade")
    score >= 60 -> println("C Grade")
    else -> println("Fail")
}
✅ Great when multiple unrelated conditions are needed.
❌ Fallthrough Doesn’t Happen in Kotlin
Each when case is isolated—no fallthrough like in Java switch.
val x = 1
when (x) {
    1 -> println("One") // only this runs
    2 -> println("Two")
}
🧠 Best Practices
| Practice | Benefit | 
|---|---|
| Prefer whenover nestedif | Cleaner and more readable | 
| Use elseblock | Handle all unexpected inputs | 
| Return value directly | Makes code concise and expressive | 
| Avoid fallthrough logic | Kotlin doesn’t allow it | 
🚫 Common Mistakes
| ❌ Mistake | ✅ Solution | 
|---|---|
| Missing elsein expression use | Always include elseif used as value | 
| Using breaklike in Java | Not needed; each case is isolated | 
| Using whenon incompatible types | Match on compatible values or use type checks | 
📌 Summary – Recap & Next Steps
The when expression is Kotlin’s powerful alternative to Java’s switch. It supports value matching, condition checks, ranges, types, and acts as an expression returning results—making it a clean, smart, and safe tool in your Kotlin toolkit.
🔍 Key Takeaways:
- whenreplaces- switchand supports multiple conditions.
- Can be used as a statement or to return a value (expression).
- Works with values, ranges, collections, and type checks.
- No fallthrough behavior—each case is self-contained.
⚙️ Practical Use:
Used in UI control, API status handling, type-based logic, and form validation in Android, backend, and multiplatform Kotlin applications.
❓ FAQs – Kotlin When Expression
❓ How is when different from Java’s switch?
✅ when supports value matching, range checking, type checking, and condition evaluation—without fallthrough or break.
❓ Can I return a value from a when expression?
✅ Yes. Use when as an expression to assign a value:
val result = when (x) { 1 -> "One" else -> "Other" }
❓ Is the else block mandatory in Kotlin when?
✅ It’s required if the when is used as an expression (to return a value), but optional if used as a statement.
❓ Can I check for multiple values in one case?
✅ Yes. Use commas to separate values:
when (letter) {
    'A', 'E', 'I' -> println("Vowel")
}
❓ Can I use when without a subject (input)?
✅ Yes. Use it for complex boolean conditions:
when {
    x > 10 -> ...
    x < 0 -> ...
}
Share Now :
