0
0
Kotlinprogramming~10 mins

When with ranges and types in Kotlin - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - When with ranges and types
Start
Evaluate expression
Check when branches in order
Is value in range?
YesExecute branch
Is value of type?
YesExecute branch
Else branch
Execute branch
The 'when' expression evaluates a value, then checks each branch in order to find a matching range or type, executes that branch, and stops.
Execution Sample
Kotlin
val x: Any = 42
when (x) {
  in 1..50 -> println("In range 1 to 50")
  is String -> println("It's a String")
  else -> println("Unknown")
}
Checks if x is in the range 1 to 50, or if x is a String, then prints a message accordingly.
Execution Table
StepExpression ValueCondition CheckedCondition ResultBranch TakenOutput
142in 1..50Truein 1..50 branchIn range 1 to 50
242is StringSkippedNoNo output
342elseSkippedNoNo output
4-End of when---
💡 First condition 'in 1..50' is true, branch executed, when ends.
Variable Tracker
VariableStartAfter Step 1After Step 4
x424242
Key Moments - 2 Insights
Why does the 'is String' branch not run even though it's after the range check?
Because the first condition 'in 1..50' is true at step 1, the when expression stops checking further branches as shown in the execution_table rows 1-4.
What happens if the value is not in any range or type checked?
The 'else' branch runs as a fallback, shown in the execution_table row 3, but here it is skipped because a previous branch matched.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the output at step 1?
A"Unknown"
B"It's a String"
C"In range 1 to 50"
DNo output
💡 Hint
Check the 'Output' column in execution_table row 1.
At which step does the when expression stop checking further branches?
AStep 1
BStep 3
CStep 2
DStep 4
💡 Hint
Look at the 'Branch Taken' and 'Condition Result' columns in execution_table rows.
If x was "Hello" instead of 42, which branch would be taken?
Ain 1..50 branch
Bis String branch
Celse branch
DNo branch
💡 Hint
Refer to the 'Condition Checked' column and think about type checking.
Concept Snapshot
when (value) {
  in range -> action  // checks if value is in range
  is Type -> action   // checks if value is of a type
  else -> action      // fallback if no match
}
Stops at first matching branch.
Full Transcript
This example shows how Kotlin's when expression works with ranges and types. It evaluates the expression, then checks each branch in order. If the value is in the specified range, it runs that branch and stops. If not, it checks if the value is of a certain type. If none match, it runs the else branch. Here, the value 42 is in the range 1 to 50, so the first branch runs and the others are skipped.