0
0
Kotlinprogramming~10 mins

When with multiple conditions in Kotlin - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - When with multiple conditions
Start
Evaluate expression
Check first condition
| Yes
Execute first branch
End
No
Check second condition
| Yes
Execute second branch
End
No
Check multiple conditions combined
| Yes
Execute combined branch
End
No
Execute else branch
End
The 'when' expression evaluates an input and checks conditions one by one, including multiple conditions combined with commas, executing the matching branch and then ending.
Execution Sample
Kotlin
val x = 3
when (x) {
  1, 2 -> println("One or Two")
  3, 4 -> println("Three or Four")
  else -> println("Other")
}
This code checks the value of x and prints a message depending on which group of values x matches.
Execution Table
StepExpression ValueCondition CheckedCondition ResultBranch TakenOutput
131, 2FalseNo
233, 4TrueYesThree or Four
33elseSkippedNo
💡 Condition '3, 4' is True, branch executed, when expression ends.
Variable Tracker
VariableStartAfter Step 1After Step 2Final
x3333
Key Moments - 2 Insights
Why does the 'when' stop checking after the first true condition?
Because 'when' executes only the first matching branch and then exits, as shown in execution_table step 2 where it stops after matching '3, 4'.
How do multiple conditions work in one branch like '1, 2 ->'?
Multiple conditions separated by commas mean 'or'. If the expression matches any of them, that branch runs, as seen in step 1 checking '1, 2'.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the output at step 2?
A"One or Two"
B"Other"
C"Three or Four"
DNo output
💡 Hint
Check the 'Output' column at step 2 in the execution_table.
At which step does the 'when' expression stop checking conditions?
AStep 2
BStep 3
CStep 1
DIt checks all steps
💡 Hint
Look at the 'Branch Taken' column to see when a branch is executed and the rest skipped.
If x was 5, which branch would be taken according to the execution table logic?
A"Three or Four"
B"Other"
C"One or Two"
DNo branch
💡 Hint
Consider that 5 does not match any listed conditions, so 'else' branch runs.
Concept Snapshot
when (value) {
  condition1, condition2 -> action1
  condition3, condition4 -> action2
  else -> defaultAction
}
- Checks conditions in order
- Multiple conditions separated by commas mean OR
- Executes first matching branch and stops
- else handles all unmatched cases
Full Transcript
The Kotlin 'when' expression evaluates a value and compares it against multiple conditions. Each condition can have multiple values separated by commas, meaning if the value matches any of them, that branch runs. The checking stops at the first true condition. If none match, the else branch runs. For example, if x is 3, it does not match '1, 2' but matches '3, 4', so it prints 'Three or Four' and stops checking further.