What if you could replace messy if-else checks with a simple, powerful tool that returns values instantly?
Why When as expression returning value in Kotlin? - Purpose & Use Cases
Imagine you have a list of fruits and you want to print a special message for each type. Without a smart tool, you write many if-else checks for each fruit manually.
This manual way is slow and messy. You might forget a case or write repeated code. It's hard to read and fix later, especially when you add more fruits.
The when expression in Kotlin lets you check many conditions clearly and returns a value directly. It makes your code shorter, easier to read, and less error-prone.
var message: String if (fruit == "Apple") { message = "You picked an apple!" } else if (fruit == "Banana") { message = "You picked a banana!" } else { message = "Unknown fruit" }
val message = when (fruit) {
"Apple" -> "You picked an apple!"
"Banana" -> "You picked a banana!"
else -> "Unknown fruit"
}You can write clean, clear code that chooses values based on many conditions without repeating yourself.
Think about a vending machine that gives different messages depending on the button pressed. Using when makes it easy to return the right message for each button.
When as expression returns a value directly, simplifying your code.
It replaces long if-else chains with clear, readable branches.
Helps avoid mistakes and makes adding new cases easy.
Practice
when expression in Kotlin return when used as an expression?Solution
Step 1: Understand
In Kotlin,whenas expressionwhencan be used as an expression that returns a value depending on which case matches.Step 2: Compare with other options
It does not always return Unit, nor a Boolean, and it requires anelsebranch to avoid exceptions, so it won't throw by default.Final Answer:
It returns a value based on the matched case. -> Option AQuick Check:
whenreturns value [OK]
when returns the matched case value [OK]- Thinking
whenalways returns Unit - Confusing
whenwithifreturning Boolean - Forgetting to add an
elsebranch
when as an expression returning a value in Kotlin?Solution
Step 1: Check correct
val result = when (x) { in 1..10 -> "Small"; else -> "Large" } useswhensyntax with argumentwhen (x)with cases separated by semicolons and anelsebranch, which is correct.Step 2: Identify syntax errors in other options
val result = when { x > 0 -> "Positive"; else -> "Non-positive" } uses semicolons inside braces correctly; val result = when (x) { x > 0 -> "Positive" else -> "Non-positive" } misses semicolon beforeelse; val result = when x { 1 -> "One"; else -> "Other" } misses parentheses aroundx.Final Answer:
val result = when (x) { in 1..10 -> "Small"; else -> "Large" } -> Option DQuick Check:
Correctwhensyntax uses parentheses and semicolons [OK]
- Omitting parentheses around the variable
- Using commas instead of semicolons
- Missing semicolon before else branch
val x = 5
val result = when {
x < 0 -> "Negative"
x == 0 -> "Zero"
x in 1..10 -> "Small"
else -> "Large"
}
println(result)Solution
Step 1: Evaluate conditions in order
x = 5 is not less than 0, not equal to 0, but is in 1..10 range, so the third case matches.Step 2: Determine returned value
The matched case returns "Small", soresultis "Small".Final Answer:
Small -> Option AQuick Check:
5 in 1..10 = true, returns "Small" [OK]
- Assuming else branch runs for 5
- Confusing equality and range checks
- Ignoring order of conditions
when as an expression:val x = 3
val result = when (x) {
1 -> "One"
2 -> "Two"
}
println(result)Solution
Step 1: Check completeness of
Thewhenexpressionwhenexpression covers only 1 and 2, but x = 3 is not handled and noelsebranch is provided.Step 2: Understand Kotlin requirement for exhaustive
When used as an expression,whenwhenmust be exhaustive, so missingelsecauses a compilation error.Final Answer:
Missingelsebranch causes compilation error. -> Option BQuick Check:
Exhaustivewhenneedselse[OK]
else if not all cases covered [OK]- Ignoring missing
elsebranch - Thinking semicolons are mandatory
- Assuming
whenalways compiles without else
when as an expression. Which code correctly returns "A" for scores 90 and above, "B" for 80-89, "C" for 70-79, and "F" otherwise?Solution
Step 1: Understand
val grade = when { score >= 90 -> "A" score >= 80 -> "B" score >= 70 -> "C" else -> "F" } useswhenwith condition expressionswhenwithout argument and conditions likescore >= 90, which is valid and clear for ranges.Step 2: Check other options for errors
val grade = when (score) { in 90..100 -> "A" in 80..89 -> "B" in 70..79 -> "C" else -> "F" } is correct syntax but uses ranges; val grade = when (score) { score >= 90 -> "A" score >= 80 -> "B" score >= 70 -> "C" else -> "F" } incorrectly uses conditions insidewhen(score)which expects values, not conditions; val grade = when { in 90..100 -> "A" in 80..89 -> "B" in 70..79 -> "C" else -> "F" } usesinwithout variable, which is invalid.Final Answer:
val grade = when { score >= 90 -> "A" score >= 80 -> "B" score >= 70 -> "C" else -> "F" } -> Option CQuick Check:
Usewhenwithout argument for conditions [OK]
when without argument for condition checks [OK]- Using conditions inside
when(variable) - Omitting variable in range checks
- Misplacing
inkeyword
Ready to prove it?
Pass the test and this pattern moves unknown
