Beginner 7 min readKotlin 2.0
Kotlin when — Pattern Matching Expression
The when expression is Kotlin's powerful replacement for switch. It matches values, ranges, and types — and returns a value when used as an expression.
What You Will Learn
- Match values with when
- Use ranges in when
- Use when without an argument
- Use when as an expression
- Check types in when
Basic when
when matches an argument against branches. The first matching branch executes.
when — Value Matching
kotlin
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")
}
}Output
Wednesday
day is 3, so the third branch matches. else is the default when no other branch matches.
Beginner Tip: when is more readable than chained if/else if when matching multiple values.
Multiple Values per Branch
Combine multiple values in one branch with commas.
Multiple Values
kotlin
fun main() {
val num = 0
when (num) {
0 -> println("Zero")
1, 2, 3 -> println("Small positive")
in 4..100 -> println("Medium")
else -> println("Large or negative")
}
}Output
Zero
1, 2, 3 matches any of those three values. in 4..100 matches any number in that range.
when as an Expression
when can return a value — assign it to a variable.
when Expression
kotlin
fun main() {
val score = 85
val grade = when {
score >= 90 -> "A"
score >= 80 -> "B"
score >= 70 -> "C"
else -> "F"
}
println(grade)
}Output
B
when without an argument evaluates each condition as a boolean. The first true branch returns its value.
Best Practice: When all branches must be covered (exhaustive), use when with a sealed class — the compiler will warn if you miss a case.
Practice Exercise
Exercisepredict output
What prints? val x = 15 when { x < 10 -> println("Small") x < 20 -> println("Medium") else -> println("Large") }
Quick Quiz
Quick Quiz
What replaces switch in Kotlin?
Frequently Asked Questions
Related Tutorials
Last updated: 2026-05-01Kotlin 2.0
Written by KotlinGuide Editorial Team · Reviewed by KotlinGuide Technical Review