0
0
Kotlinprogramming~10 mins

When without argument in Kotlin - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - When without argument
Start
Evaluate conditions one by one
If condition true?
NoCheck next condition
Yes
Execute corresponding block
Exit when block executed
End
The 'when' without argument checks each condition in order and runs the block for the first true condition, then stops.
Execution Sample
Kotlin
val x = 15
when {
  x < 10 -> println("Less than 10")
  x in 10..20 -> println("Between 10 and 20")
  else -> println("More than 20")
}
This code checks x against conditions without an argument and prints the matching message.
Execution Table
StepCondition CheckedCondition ResultAction TakenOutput
1x < 10falseCheck next condition
2x in 10..20trueExecute blockBetween 10 and 20
3ExitN/AStop checking further
💡 Condition 'x in 10..20' is true, so execution stops after this block.
Variable Tracker
VariableStartAfter Step 1After Step 2Final
x15151515
Key Moments - 2 Insights
Why does the 'when' stop after the second condition even though there is an 'else'?
Because the second condition 'x in 10..20' is true, the corresponding block runs and 'when' exits immediately without checking 'else' (see execution_table row 2 and 3).
What happens if none of the conditions are true and there is no 'else'?
The 'when' expression does nothing and no block runs, because it only executes the first true condition block (not shown in this example but implied by the flow).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the result of checking 'x < 10' at step 1?
Atrue
Bfalse
Cerror
Dnot evaluated
💡 Hint
Check the 'Condition Result' column at step 1 in the execution_table.
At which step does the 'when' expression stop checking conditions?
AStep 1
BStep 3
CStep 2
DIt never stops
💡 Hint
Look at the 'Action Taken' and 'Exit' rows in the execution_table.
If x was 25, which output would appear according to the execution flow?
AMore than 20
BBetween 10 and 20
CLess than 10
DNo output
💡 Hint
Think about which condition would be true if x=25, based on the conditions in the code sample.
Concept Snapshot
when without argument:
- Checks each condition in order
- Executes block for first true condition
- Stops after executing one block
- 'else' acts as default if no conditions true
- Useful for complex condition checks without a single value
Full Transcript
The Kotlin 'when' expression without an argument works by checking each condition one by one. It runs the block for the first condition that is true and then stops checking further. For example, if x is 15, it first checks if x < 10, which is false, then checks if x is between 10 and 20, which is true, so it prints 'Between 10 and 20' and stops. If none of the conditions are true and there is an 'else' block, it runs that as a default. This makes 'when' without argument a flexible way to handle multiple conditions clearly and simply.