
When Expression in Kotlin
📌 when
Expression in Kotlin
In Kotlin, the when
expression is a more powerful and flexible version of the traditional switch
statement found in other languages. It is often used to replace multiple if-else-if statements for cleaner and more readable code.
✅ Syntax of when
val number = 5when (number) { 1, 2, 3 -> println("Small Number") 4, 5, 6 -> println("Medium Number") else -> println("Large Number")}
Output:
Medium Number
✅ 3. Using Ranges and Conditions
when
supports range checks using the in
and !in
operators.
val age = 25when (age) { in 0..12 -> println("Child") in 13..19 -> println("Teenager") in 20..59 -> println("Adult") else -> println("Senior")}
Output:
✅ 4. Using when
Without an Argument
You can use when
without an argument by using Boolean conditions.
val number = 15when { number % 2 == 0 -> println("Even Number") number % 2 != 0 -> println("Odd Number") else -> println("Unknown")}
Output:
Odd Number
✅ 5. Using when
as an Expression
when
can return a value directly.
val grade = 'B'val result = when (grade) { 'A' -> "Excellent" 'B' -> "Good" 'C' -> "Average" else -> "Fail"}println("Result: $result")
Output:
fun (obj: Any) { Unknown Type
✅ 7. Smart Casting in when
Kotlin performs smart casting inside when
if it recognizes a type.
fun (obj: Any) { when (obj) { is String -> println("Length: ${obj.length}") is Int -> println("Double Value: ${obj * 2}") else -> println("Unknown") }}describe("Hello")describe(7)
Output:
Length: 5Double Value: 14
✅ Conclusion
when
is more readable and powerful than traditionalswitch
.Supports multiple conditions, ranges, and type checking.
Can be used as an expression to return a value.
Eliminates the need for repetitive
if-else
statements.