Bird
Raised Fist0
Kotlinprogramming~10 mins

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

Choose your learning style10 modes available
Concept Flow - When with ranges and types
Start
↓
Evaluate expression
↓
Check when branches in order
↓
Is value in range?
Yes→Execute branch
↓
Is value of type?
Yes→Execute 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.

Practice

(1/5)
1. What does the when expression in Kotlin do when used with ranges like in 1..5?
easy
A. It throws an error if the value is outside the range.
B. It creates a new range from 1 to 5.
C. It assigns the value to the range variable.
D. It checks if the value falls within the specified range.

Solution

  1. Step 1: Understand the when with range syntax

    The syntax in 1..5 inside when checks if the value is between 1 and 5 inclusive.
  2. Step 2: Interpret the check

    If the value is inside the range, the corresponding branch executes; otherwise, it moves to the next case.
  3. Final Answer:

    It checks if the value falls within the specified range. -> Option D
  4. Quick Check:

    when with in checks range membership [OK]
Hint: Remember: in means inside the range [OK]
Common Mistakes:
  • Thinking in creates a range instead of checking membership
  • Confusing in with assignment
  • Assuming it throws errors for out-of-range values
2. Which of the following is the correct syntax to check if a variable x is NOT in the range 10 to 20 using when in Kotlin?
easy
A. when(x) { !in 10..20 -> "Outside" }
B. when(x) { not in 10..20 -> "Outside" }
C. when(x) { x !in 10..20 -> "Outside" }
D. when(x) { outside 10..20 -> "Outside" }

Solution

  1. Step 1: Recall the correct negation syntax in when

    In Kotlin, !in is used to check if a value is NOT in a range.
  2. Step 2: Match the syntax with options

    when(x) { !in 10..20 -> "Outside" } uses !in 10..20 correctly inside when. Other options use invalid keywords or syntax.
  3. Final Answer:

    when(x) { !in 10..20 -> "Outside" } -> Option A
  4. Quick Check:

    Use !in to check exclusion from range [OK]
Hint: Use !in to say NOT in range [OK]
Common Mistakes:
  • Using 'not in' instead of '!in'
  • Writing variable name inside when case
  • Using undefined keywords like 'outside'
3. What will be the output of this Kotlin code?
val x: Any = 42
val result = when (x) {
  is Int -> "Integer"
  in 1..10 -> "Small number"
  else -> "Unknown"
}
println(result)
medium
A. Small number
B. Unknown
C. Integer
D. Compilation error

Solution

  1. Step 1: Check the type of x

    Variable x is of type Any but holds the value 42, which is an Int.
  2. Step 2: Evaluate when branches in order

    The first branch checks is Int, which is true, so it returns "Integer". The second branch is not checked because the first matched.
  3. Final Answer:

    Integer -> Option C
  4. Quick Check:

    when matches first true branch [OK]
Hint: Type checks with is come before range checks [OK]
Common Mistakes:
  • Assuming range check runs before type check
  • Confusing value 42 as outside 1..10
  • Thinking when checks all branches
4. Identify the error in this Kotlin when expression:
val y: Any = "Hello"
val output = when (y) {
  in 1..5 -> "Number"
  is String -> "Text"
  else -> "Other"
}
println(output)
medium
A. Cannot use in with Any type without casting
B. The is String check should come before the range check
C. Missing break statements in when
D. No error, code runs fine

Solution

  1. Step 1: Analyze the in 1..5 check on Any

    The variable y is of type Any. The in operator with ranges requires a comparable type like Int. Using in 1..5 on Any causes a type mismatch error.
  2. Step 2: Check order of branches and syntax

    The is String check is valid but unreachable if the first branch errors. Also, when in Kotlin does not require break.
  3. Final Answer:

    Cannot use in with Any type without casting -> Option A
  4. Quick Check:

    Range checks need compatible types [OK]
Hint: Check variable type before using in with ranges [OK]
Common Mistakes:
  • Ignoring type mismatch for in operator
  • Thinking when needs break
  • Assuming order of branches causes error
5. You want to write a Kotlin when expression that returns:
- "Small Int" if the value is an Int between 1 and 10 inclusive,
- "Large Int" if the value is an Int greater than 10,
- "String" if the value is a String,
- "Other" for anything else.

Which of the following when expressions correctly implements this?
hard
A. when (v) { in 1..10 -> "Small Int" is Int -> "Large Int" is String -> "String" else -> "Other" }
B. when (v) { is Int -> if (v in 1..10) "Small Int" else "Large Int" is String -> "String" else -> "Other" }
C. when (v) { is Int in 1..10 -> "Small Int" is Int -> "Large Int" is String -> "String" else -> "Other" }
D. when (v) { is Int && v in 1..10 -> "Small Int" is Int -> "Large Int" is String -> "String" else -> "Other" }

Solution

  1. Step 1: Understand the conditions needed

    We need to check if v is an Int and then check its value range for "Small Int" or "Large Int". Also check if v is a String.
  2. Step 2: Analyze each option's correctness

    when (v) { in 1..10 -> "Small Int" is Int -> "Large Int" is String -> "String" else -> "Other" } incorrectly uses in 1..10 without checking type first, causing errors if v is not Int. when (v) { is Int in 1..10 -> "Small Int" is Int -> "Large Int" is String -> "String" else -> "Other" } uses invalid syntax is Int in 1..10. when (v) { is Int && v in 1..10 -> "Small Int" is Int -> "Large Int" is String -> "String" else -> "Other" } uses invalid syntax is Int && v in 1..10 inside when. when (v) { is Int -> if (v in 1..10) "Small Int" else "Large Int" is String -> "String" else -> "Other" } correctly checks type first, then uses an if inside the branch to distinguish ranges.
  3. Final Answer:

    Option B correctly implements the logic. -> Option B
  4. Quick Check:

    Use nested if inside when for complex conditions [OK]
Hint: Check type first, then range inside branch with if [OK]
Common Mistakes:
  • Using invalid syntax combining is and in
  • Not checking type before range
  • Trying to use logical operators directly in when cases
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