when
Expression in Kotlinwhen
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!
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! π") } }
day
to 6 or 7. What gets printed?
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 π") } }
today = "Friday"
? Try to guess before running.
when
as an ExpressionJust 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") }
when
to return a grade based on temperature ranges.
when
Without an ArgumentYou 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 π§") } }
age
to 15. See the result.
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 π§") } }
"Blue"
and see how else
works.
when
replaces switch and supports ranges, types, expressions.when
!
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!