How do I use the when expression as a switch alternative in Kotlin?

In Kotlin, the when expression can be used as an alternative to the traditional switch statement found in languages like Java. The when expression is versatile, concise, and supports a wide range of matching conditions. Here’s how you can use it:

Examples of Using the when Expression

  1. Using when as a simple switch:
    fun getResponse(code: Int): String {
       return when (code) {
           200 -> "OK"
           404 -> "Not Found"
           500 -> "Internal Server Error"
           else -> "Unknown Code"
       }
    }
    
  2. Multiple matches for a single branch:
    You can check multiple values by separating them with a comma.

    fun isWeekend(day: String): Boolean {
       return when (day) {
           "Saturday", "Sunday" -> true
           else -> false
       }
    }
    
  3. Range checking:
    You can check if a value falls within a certain range.

    fun categorizeAge(age: Int): String {
       return when (age) {
           in 0..12 -> "Child"
           in 13..19 -> "Teenager"
           in 20..59 -> "Adult"
           else -> "Senior"
       }
    }
    
  4. Type checking:
    The is keyword can be used to check the type of a variable.

    fun describe(obj: Any): String {
       return when (obj) {
           is String -> "It's a string of length ${obj.length}"
           is Int -> "It's an integer"
           else -> "Unknown type"
       }
    }
    
  5. Checking conditions (arbitrary boolean expressions):
    You can use boolean expressions inside the when expression.

    fun checkNumber(num: Int): String {
       return when {
           num < 0 -> "Negative Number"
           num == 0 -> "Zero"
           num > 0 -> "Positive Number"
           else -> "Unknown"
       }
    }
    
  6. when without an argument:
    You can omit the argument from when if you just want to match conditions.

    fun getResult(value: Int): String {
       return when {
           value % 2 == 0 -> "Even"
           value % 2 != 0 -> "Odd"
           else -> "Unknown"
       }
    }
    

when as an Expression vs Statement

In Kotlin, when is an expression, which means it can return a value:

val message = when (val age = 25) {
    in 0..12 -> "You're a child"
    in 13..19 -> "You're a teenager"
    else -> "You're an adult"
}
println(message)

But you can also use it as a statement if you don’t need the result:

fun printMessage(code: Int) {
    when (code) {
        200 -> println("Request was successful")
        404 -> println("Resource not found")
        else -> println("Unexpected response code")
    }
}

Summary

The when expression in Kotlin allows for cleaner and more expressive code compared to a traditional switch statement. It supports:

  • Multiple case matching.
  • Type checking.
  • Arbitrary conditions.
  • Use as a statement or an expression.

This flexibility makes it a powerful tool for decision-making in Kotlin!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.