Bird
Raised Fist0
Kotlinprogramming~10 mins

When as expression returning value in Kotlin - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - When as expression returning value
Start
↓
Evaluate input
↓
Match case 1?
No→Match case 2?
↓
Return value 1
↓
End with returned value
The 'when' expression evaluates a value and returns a result from the matching branch, acting like a switch that produces a value.
Execution Sample
Kotlin
val result = when (x) {
  1 -> "One"
  2 -> "Two"
  else -> "Other"
}
println(result)
This code uses 'when' to return a string based on x's value and prints the result.
Execution Table
StepInput xCondition CheckedMatch ResultReturned ValueOutput
11x == 1Yes"One""One"
22x == 1 (No), x == 2 (Yes)Yes"Two""Two"
33x == 1 (No), x == 2 (No), elseYes"Other""Other"
💡 Execution stops after returning the matched value from 'when' expression.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3
xvaries123
resultuninitialized"One""Two""Other"
Key Moments - 2 Insights
Why does 'when' return a value instead of just running code?
'when' in Kotlin is an expression, not just a statement, so it evaluates to the value of the matched branch, as shown in the execution_table where 'result' gets assigned the returned value.
What happens if no case matches and there is no 'else'?
Without an 'else', if no case matches, the code will not compile because 'when' must be exhaustive when used as an expression, ensuring a value is always returned.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the returned value when x is 2?
A"One"
B"Other"
C"Two"
Dnull
💡 Hint
Check row 2 in execution_table under 'Returned Value' column.
At which step does the 'else' branch return a value?
AStep 3
BStep 2
CStep 1
DNever
💡 Hint
Look at the 'Condition Checked' column in execution_table for step 3.
If x was 1, what would be the value of 'result' after execution?
A"Two"
B"One"
C"Other"
Duninitialized
💡 Hint
Refer to variable_tracker row for 'result' after step 1.
Concept Snapshot
when (value) {
  case1 -> result1
  case2 -> result2
  else -> defaultResult
}

- 'when' evaluates the input and returns the matched branch's value.
- Must be exhaustive if used as expression (include 'else').
- Assign result directly from 'when'.
Full Transcript
The Kotlin 'when' expression checks a value against multiple cases and returns the value of the matched case. It works like a switch but produces a value that can be assigned to a variable. Each step evaluates conditions in order until one matches, then returns its value. If no cases match, the 'else' branch provides a default value. This ensures the expression always returns something. The execution table shows how different inputs lead to different returned values, and the variable tracker shows how the result variable changes accordingly. Remember, 'when' must be exhaustive when used as an expression, so always include an 'else' case if not all values are covered.

Practice

(1/5)
1. What does the when expression in Kotlin return when used as an expression?
easy
A. It returns a value based on the matched case.
B. It always returns Unit (no value).
C. It returns a Boolean indicating if a case matched.
D. It throws an exception if no case matches.

Solution

  1. Step 1: Understand when as expression

    In Kotlin, when can be used as an expression that returns a value depending on which case matches.
  2. Step 2: Compare with other options

    It does not always return Unit, nor a Boolean, and it requires an else branch to avoid exceptions, so it won't throw by default.
  3. Final Answer:

    It returns a value based on the matched case. -> Option A
  4. Quick Check:

    when returns value [OK]
Hint: Remember: when returns the matched case value [OK]
Common Mistakes:
  • Thinking when always returns Unit
  • Confusing when with if returning Boolean
  • Forgetting to add an else branch
2. Which of the following is the correct syntax to use when as an expression returning a value in Kotlin?
easy
A. val result = when x { 1 -> "One"; else -> "Other" }
B. val result = when (x) { x > 0 -> "Positive" else -> "Non-positive" }
C. val result = when { x > 0 -> "Positive"; else -> "Non-positive" }
D. val result = when (x) { in 1..10 -> "Small"; else -> "Large" }

Solution

  1. Step 1: Check correct when syntax with argument

    val result = when (x) { in 1..10 -> "Small"; else -> "Large" } uses when (x) with cases separated by semicolons and an else branch, which is correct.
  2. 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 before else; val result = when x { 1 -> "One"; else -> "Other" } misses parentheses around x.
  3. Final Answer:

    val result = when (x) { in 1..10 -> "Small"; else -> "Large" } -> Option D
  4. Quick Check:

    Correct when syntax uses parentheses and semicolons [OK]
Hint: Use parentheses around variable and semicolons between cases [OK]
Common Mistakes:
  • Omitting parentheses around the variable
  • Using commas instead of semicolons
  • Missing semicolon before else branch
3. What is the output of the following Kotlin code?
val x = 5
val result = when {
  x < 0 -> "Negative"
  x == 0 -> "Zero"
  x in 1..10 -> "Small"
  else -> "Large"
}
println(result)
medium
A. Small
B. Zero
C. Negative
D. Large

Solution

  1. 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.
  2. Step 2: Determine returned value

    The matched case returns "Small", so result is "Small".
  3. Final Answer:

    Small -> Option A
  4. Quick Check:

    5 in 1..10 = true, returns "Small" [OK]
Hint: Check conditions top to bottom; first true case returns value [OK]
Common Mistakes:
  • Assuming else branch runs for 5
  • Confusing equality and range checks
  • Ignoring order of conditions
4. Identify the error in this Kotlin code using when as an expression:
val x = 3
val result = when (x) {
  1 -> "One"
  2 -> "Two"
}
println(result)
medium
A. Incorrect variable name in when.
B. Missing else branch causes compilation error.
C. Semicolons missing between cases.
D. Cannot use when as expression.

Solution

  1. Step 1: Check completeness of when expression

    The when expression covers only 1 and 2, but x = 3 is not handled and no else branch is provided.
  2. Step 2: Understand Kotlin requirement for exhaustive when

    When used as an expression, when must be exhaustive, so missing else causes a compilation error.
  3. Final Answer:

    Missing else branch causes compilation error. -> Option B
  4. Quick Check:

    Exhaustive when needs else [OK]
Hint: Always add else if not all cases covered [OK]
Common Mistakes:
  • Ignoring missing else branch
  • Thinking semicolons are mandatory
  • Assuming when always compiles without else
5. You want to assign a grade based on a score using 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?
hard
A. val grade = when (score) { score >= 90 -> "A" score >= 80 -> "B" score >= 70 -> "C" else -> "F" }
B. val grade = when (score) { in 90..100 -> "A" in 80..89 -> "B" in 70..79 -> "C" else -> "F" }
C. val grade = when { score >= 90 -> "A" score >= 80 -> "B" score >= 70 -> "C" else -> "F" }
D. val grade = when { in 90..100 -> "A" in 80..89 -> "B" in 70..79 -> "C" else -> "F" }

Solution

  1. Step 1: Understand when with condition expressions

    val grade = when { score >= 90 -> "A" score >= 80 -> "B" score >= 70 -> "C" else -> "F" } uses when without argument and conditions like score >= 90, which is valid and clear for ranges.
  2. 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 inside when(score) which expects values, not conditions; val grade = when { in 90..100 -> "A" in 80..89 -> "B" in 70..79 -> "C" else -> "F" } uses in without variable, which is invalid.
  3. Final Answer:

    val grade = when { score >= 90 -> "A" score >= 80 -> "B" score >= 70 -> "C" else -> "F" } -> Option C
  4. Quick Check:

    Use when without argument for conditions [OK]
Hint: Use when without argument for condition checks [OK]
Common Mistakes:
  • Using conditions inside when(variable)
  • Omitting variable in range checks
  • Misplacing in keyword
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard