Kotlin When Expression
Powerful alternative to multiple if-else statements
🎯 What is When Expression?
When expression is Kotlin's powerful replacement for switch statements. It matches a value against multiple conditions and executes corresponding code, making complex decision-making cleaner and more readable than multiple if-else chains.
// Simple when expression
val day = 3
when (day) {
1 -> println("Monday")
2 -> println("Tuesday")
3 -> println("Wednesday")
}
When Expression Features
Value Matching
Match exact values
when (x) {
1 -> "One"
2 -> "Two"
else -> "Other"
}
Range Matching
Match ranges of values
when (score) {
in 90..100 -> "A"
in 80..89 -> "B"
else -> "C"
}
Type Checking
Match by data type
when (obj) {
is String -> "Text"
is Int -> "Number"
else -> "Unknown"
}
Expression
Return values directly
val result = when (grade) {
'A' -> "Excellent"
'B' -> "Good"
else -> "Try harder"
}
🔹 Basic When Expression
Match specific values:
fun main() {
val dayOfWeek = 5
when (dayOfWeek) {
1 -> println("Monday - Start of work week")
2 -> println("Tuesday - Getting into rhythm")
3 -> println("Wednesday - Hump day!")
4 -> println("Thursday - Almost there")
5 -> println("Friday - TGIF!")
6, 7 -> println("Weekend - Time to relax!")
else -> println("Invalid day")
}
}
Output:
Friday - TGIF!
🔹 When as Expression
Return values from when expression:
fun main() {
val grade = 'B'
val description = when (grade) {
'A' -> "Outstanding work!"
'B' -> "Good job!"
'C' -> "Satisfactory"
'D' -> "Needs improvement"
'F' -> "Failed"
else -> "Invalid grade"
}
println("Grade $grade: $description")
}
Output:
Grade B: Good job!
🔹 Range Matching
Match ranges of values using 'in':
fun main() {
val temperature = 25
val weather = when (temperature) {
in -10..0 -> "Freezing cold!"
in 1..15 -> "Cold"
in 16..25 -> "Pleasant"
in 26..35 -> "Hot"
else -> "Extreme temperature!"
}
println("$temperature°C is $weather")
}
Output:
25°C is Pleasant
🔹 Type Checking
Match by data type using 'is':
fun main() {
val items = listOf("Hello", 42, 3.14, true)
for (item in items) {
val type = when (item) {
is String -> "Text: '$item'"
is Int -> "Integer: $item"
is Double -> "Decimal: $item"
is Boolean -> "Boolean: $item"
else -> "Unknown type"
}
println(type)
}
}
Output:
Text: 'Hello'
Integer: 42
Decimal: 3.14
Boolean: true
🔹 When Without Argument
Use when like if-else chain:
fun main() {
val age = 20
val hasJob = true
val status = when {
age < 18 -> "Minor"
age >= 18 && !hasJob -> "Adult, unemployed"
age >= 18 && hasJob -> "Working adult"
age >= 65 -> "Senior citizen"
else -> "Unknown status"
}
println("Status: $status")
}
Output:
Status: Working adult
🔹 Multiple Values
Match multiple values in one branch:
fun main() {
val month = "December"
val season = when (month) {
"December", "January", "February" -> "Winter"
"March", "April", "May" -> "Spring"
"June", "July", "August" -> "Summer"
"September", "October", "November" -> "Fall"
else -> "Unknown month"
}
println("$month is in $season")
}
Output:
December is in Winter