Lesson 6 of 17

When Expressions

when in Kotlin

when is Kotlin's pattern-matching construct — like a switch statement, but more powerful. It's also an expression that returns a value:

val day = when (n) {
    1 -> "Monday"
    2 -> "Tuesday"
    3 -> "Wednesday"
    else -> "Other"
}

Each branch uses -> to separate the pattern from the result. The else branch is required when when is used as an expression.

You can match multiple values in one branch:

val type = when (n) {
    1, 2, 3 -> "small"
    else -> "large"
}

Your Turn

Write a function season(month: Int): String that returns the season for a given month number (1–12). Use: Dec/Jan/Feb → "Winter", Mar/Apr/May → "Spring", Jun/Jul/Aug → "Summer", Sep/Oct/Nov → "Autumn".

JS Transpiler loading...
Loading...
Click "Run" to execute your code.