0
0
Kotlinprogramming~10 mins

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

Choose your learning style9 modes available
Concept Flow - When as expression returning value
Start
Evaluate input
Match case 1?
NoMatch 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.