Menu
Coddy logo textTech

When Expression

Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 32 of 93.

When you have multiple specific values to check against, long chains of else if statements can become hard to read. Kotlin provides the when expression as a cleaner alternative for matching a value against multiple possibilities.

fun main() {
    val day = 3
    
    val dayName = when (day) {
        1 -> "Monday"
        2 -> "Tuesday"
        3 -> "Wednesday"
        4 -> "Thursday"
        5 -> "Friday"
        else -> "Weekend"
    }
    
    println(dayName)  // Prints: Wednesday
}

The when expression takes a value and compares it against each branch. When a match is found, the corresponding result is returned. The else branch handles any value that doesn't match the listed cases.

You can also match multiple values in a single branch by separating them with commas:

fun main() {
    val day = 6
    
    val type = when (day) {
        1, 2, 3, 4, 5 -> "Weekday"
        6, 7 -> "Weekend"
        else -> "Invalid"
    }
    
    println(type)  // Prints: Weekend
}

A value-producing when must be exhaustive: every possible input must have a result. These integer examples need else, but a Boolean when with both true and false branches does not.

challenge icon

Challenge

Easy

You are provided with the following variable:

val month = 4

Use a when expression to determine the season based on the month number and store the result in a variable called season.

Conditions:

  • Months 12, 1, 2 should return "Winter"
  • Months 3, 4, 5 should return "Spring"
  • Months 6, 7, 8 should return "Summer"
  • Months 9, 10, 11 should return "Fall"
  • Any other value should return "Invalid month"

Use comma-separated values in your when branches to group months that belong to the same season.

Print the value of season.

Try it yourself

fun main() {
    val month = 4
    
    // TODO: Write your code below
    // Use a when expression to determine the season based on the month
    // Store the result in a variable called 'season'
    
    
    // Print the result
    println(season)
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals

Practice on your own: Kotlin playground