0
0
Kotlinprogramming~5 mins

When as expression returning value in Kotlin

Choose your learning style9 modes available
Introduction

The when expression in Kotlin lets you choose a value based on conditions. It returns a result, so you can use it directly where a value is needed.

Choosing a message to show based on a user's age
Setting a color based on a traffic light signal
Returning a discount percentage based on customer type
Picking an action based on a button clicked
Syntax
Kotlin
val result = when (variable) {
    condition1 -> value1
    condition2 -> value2
    else -> defaultValue
}

The when expression returns the value of the matched branch.

You must cover all cases or use else as a fallback.

Examples
Returns "Weekend" if day is Saturday or Sunday, otherwise "Weekday".
Kotlin
val dayType = when (day) {
    "Saturday", "Sunday" -> "Weekend"
    else -> "Weekday"
}
Uses conditions without a variable to check if x is positive, negative, or zero.
Kotlin
val numberType = when {
    x > 0 -> "Positive"
    x < 0 -> "Negative"
    else -> "Zero"
}
Sample Program

This program assigns a letter grade based on the numeric score using when as an expression.

Kotlin
fun main() {
    val score = 85
    val grade = when (score) {
        in 90..100 -> "A"
        in 80..89 -> "B"
        in 70..79 -> "C"
        in 60..69 -> "D"
        else -> "F"
    }
    println("Score: $score")
    println("Grade: $grade")
}
OutputSuccess
Important Notes

You can use multiple conditions separated by commas in one branch.

The when expression is like a smarter switch that returns a value.

Summary

when can return a value directly.

Use it to replace multiple if-else statements for clearer code.

Always handle all cases or provide an else branch.