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
EasyYou are provided with the following variable:
val month = 4Use 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,2should return"Winter" - Months
3,4,5should return"Spring" - Months
6,7,8should return"Summer" - Months
9,10,11should 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)
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorAugmented AssignmentComparison OperatorsRecap - Simple Math7Basic IO
Println FunctionString TemplatesReadLine InputType ConversionRecap - Years Until RetirementRecap - True or False10Functions
Declare A FunctionParameters And ArgumentsReturn ValuesNamed ArgumentsDefault ValuesSingle Expression FunctionsRecap - Sigma FunctionRecap - Validation Function2Variables
Val vs VarType InferenceNumbersStringBooleanNaming ConventionsRecap - Initialize Variables5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Logical Operators Part 3Ternary With If ExpressionRecap - Simple Logic8Bill Split Calculator
Welcome MessageGetting Input3Nullability
What Is Null SafetyNullable TypesSafe Call OperatorElvis OperatorFunction Challenge BasicsNot Null AssertionRecap - Safe Access6Decision Making
If StatementIf - ElseIf As An ExpressionWhen ExpressionWhen With RangesRecap - Simple Calculator9Loops
For LoopWhile LoopDo-While LoopBreakContinueRanges In LoopsNested LoopRecap - FactorialRecap - Dynamic InputPractice on your own: Kotlin playground