KOTLIN Tutorial



WHEN EXPRESSION


πŸ”„ when Expression in Kotlin

when is Kotlin’s version of the switch-case, but much more flexible and powerful. It can be used as a statement or an expression to return values. Let’s dive in!


1️⃣ Basic Usage

Let’s see how when works with simple conditions:

fun main() {
    val day = 3

    when (day) {
        1 -> println("Monday 😴")
        2 -> println("Tuesday πŸ’€")
        3 -> println("Wednesday 🐫")
        4 -> println("Thursday πŸ“š")
        5 -> println("Friday πŸ₯³")
        else -> println("Weekend! πŸŽ‰")
    }
}
  
βœ… Try this: Change day to 6 or 7. What gets printed?

2️⃣ Multiple Options in a Single Case

You can group multiple values in one branch:

fun main() {
    val today = "Saturday"

    when (today) {
        "Saturday", "Sunday" -> println("Weekend Vibes! 😎")
        "Monday" -> println("Back to work 😩")
        else -> println("Regular day 😐")
    }
}
  
πŸ” Think: What if today = "Friday"? Try to guess before running.

3️⃣ when as an Expression

Just like if, when can also return a value:

fun main() {
    val score = 92

    val grade = when {
        score >= 90 -> "A 🌟"
        score >= 75 -> "B πŸ‘"
        score >= 60 -> "C πŸ™‚"
        else -> "D 😬"
    }

    println("Grade: $grade")
}
  
🧠 Challenge: Use when to return a grade based on temperature ranges.

4️⃣ Using when Without an Argument

You can use when without directly checking a variable:

fun main() {
    val age = 25

    when {
        age < 13 -> println("Child πŸ‘Ά")
        age in 13..19 -> println("Teenager πŸ‘¦")
        age >= 20 -> println("Adult πŸ§‘")
    }
}
  
✍️ Try: Change age to 15. See the result.

5️⃣ Real-World Use Case: Traffic Lights 🚦

Let’s simulate traffic signals:

fun main() {
    val signal = "Green"

    when (signal.lowercase()) {
        "red" -> println("STOP ❌")
        "yellow" -> println("SLOW DOWN ⚠️")
        "green" -> println("GO βœ…")
        else -> println("Unknown Signal 🚧")
    }
}
  
πŸ§ͺ Experiment: Add "Blue" and see how else works.

6️⃣ Summary

  • βœ”οΈ when replaces switch and supports ranges, types, expressions.
  • βœ”οΈ Use it with or without a subject.
  • βœ”οΈ Cleaner, smarter, and Kotlin-idiomatic.
🏁 Mastered: You now know how to make decisions with elegance using when!

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review