Bird
Raised Fist0
Kotlinprogramming~10 mins

When expression as powerful switch in Kotlin - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - When expression as powerful switch
Start
↓
Evaluate expression
↓
Match case 1?
No→Match case 2?
↓
Execute case 1
↓
Return result
↓
End
The when expression evaluates a value and matches it against multiple cases, executing the first matching case or else the default else case, then returns the result.
Execution Sample
Kotlin
val x = 2
val result = when (x) {
  1 -> "One"
  2 -> "Two"
  3 -> "Three"
  else -> "Unknown"
}
This code checks the value of x and returns a string matching the number or "Unknown" if no match.
Execution Table
StepExpression ValueCase CheckedMatch?ActionResult
121NoCheck next case
222YesReturn "Two""Two"
33SkippedSkipped"Two"
4elseSkippedSkipped"Two"
💡 Match found at case 2, returned "Two", execution stops.
Variable Tracker
VariableStartAfter Step 1After Step 2Final
x2222
resultundefinedundefined"Two""Two"
Key Moments - 3 Insights
Why does the when expression stop checking cases after finding a match?
Because when acts like a switch, it executes only the first matching case and then returns immediately, as shown in execution_table row 2.
What happens if none of the cases match and there is no else branch?
The when expression will throw an exception if no else branch is provided and no case matches. The else branch acts as a default to avoid this.
Can when expression return a value?
Yes, when is an expression that returns the value of the matched case, as shown by the 'result' variable in variable_tracker.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the result after step 2?
A"Two"
B"One"
C"Three"
D"Unknown"
💡 Hint
Check the 'Result' column at step 2 in the execution_table.
At which step does the when expression stop checking further cases?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look at the 'Match?' column and see where 'Yes' appears first in execution_table.
If x was 5, which case would be executed?
ACase 1
BCase 2
CCase 3
DElse case
💡 Hint
Refer to the concept_flow and execution_table logic for unmatched values.
Concept Snapshot
when (value) {
  case1 -> result1
  case2 -> result2
  ...
  else -> defaultResult
}

- Evaluates value once
- Matches cases top to bottom
- Executes first matching case
- Returns the matched case's result
- else is mandatory if cases don't cover all values
Full Transcript
The when expression in Kotlin works like a powerful switch statement. It evaluates a value once and checks it against multiple cases in order. When it finds the first matching case, it executes that case and returns its result immediately, skipping the rest. If no cases match, the else branch runs as a default. This makes when concise and expressive for branching logic. In the example, x is 2, so when matches case 2 and returns "Two". Variables track the value of x and the result returned. The execution table shows step-by-step how each case is checked and when the match happens. This helps beginners see how when stops checking after the first match and how the result is assigned. Remember to always include else if your cases don't cover all possibilities to avoid errors.

Practice

(1/5)
1. What is the main purpose of the when expression in Kotlin?
easy
A. To define functions with multiple parameters
B. To create loops that repeat actions multiple times
C. To select actions based on different values, like a switch statement
D. To declare variables with different types

Solution

  1. Step 1: Understand the role of when

    The when expression is used to choose between different actions depending on the value it checks.
  2. Step 2: Compare with other options

    The other options describe loops, functions, and variables, which are unrelated to when.
  3. Final Answer:

    To select actions based on different values, like a switch statement -> Option C
  4. Quick Check:

    when chooses actions by value [OK]
Hint: Think of when as a smarter switch [OK]
Common Mistakes:
  • Confusing when with loops
  • Thinking when declares variables
  • Mixing when with function definitions
2. Which of the following is the correct syntax for a simple when expression in Kotlin?
easy
A. when x { 1: println("One") 2: println("Two") else: println("Other") }
B. switch (x) { case 1: println("One") case 2: println("Two") default: println("Other") }
C. if (x == 1) println("One") else if (x == 2) println("Two") else println("Other")
D. when (x) { 1 -> println("One") 2 -> println("Two") else -> println("Other") }

Solution

  1. Step 1: Identify Kotlin when syntax

    The correct syntax uses when (x) { value -> action } with arrows and braces.
  2. Step 2: Check other options

    when x { 1: println("One") 2: println("Two") else: println("Other") } uses colons (:) instead of arrows (->) and lacks parentheses. switch (x) { case 1: ... } is Java or JavaScript syntax. if (x == 1) ... is an if-else chain.
  3. Final Answer:

    when (x) { 1 -> println("One") 2 -> println("Two") else -> println("Other") } -> Option D
  4. Quick Check:

    Kotlin when uses arrows and braces [OK]
Hint: Look for arrows (->) inside braces for when [OK]
Common Mistakes:
  • Using colon (:) instead of arrow (->)
  • Confusing when with switch syntax
  • Omitting parentheses around the variable
3. What will be the output of the following Kotlin code?
val x = 3
when (x) {
  1, 2 -> println("Small")
  in 3..5 -> println("Medium")
  else -> println("Large")
}
medium
A. Medium
B. Small
C. Large
D. No output (runtime error)

Solution

  1. Step 1: Check the value of x

    The variable x is 3.
  2. Step 2: Match x with when cases

    3 is not in 1 or 2, but it is in the range 3..5, so "Medium" is printed.
  3. Final Answer:

    Medium -> Option A
  4. Quick Check:

    3 in 3..5 means output is "Medium" [OK]
Hint: Check ranges and multiple values carefully [OK]
Common Mistakes:
  • Ignoring ranges and picking wrong case
  • Assuming 3 matches 1 or 2
  • Thinking else runs when a range matches
4. Identify the error in this Kotlin when expression:
val y = 10
when y {
  5 -> println("Five")
  10 -> println("Ten")
  else -> println("Other")
}
medium
A. Missing parentheses around y in when
B. Missing arrow (->) after else
C. Using when without braces
D. No error, code is correct

Solution

  1. Step 1: Check when syntax

    The when expression requires parentheses around the variable: when (y).
  2. Step 2: Check other syntax parts

    Braces are present. Arrows (->) are correctly used after all cases including else. The syntax error is missing parentheses around y.
  3. Final Answer:

    Missing parentheses around y in when -> Option A
  4. Quick Check:

    when needs parentheses around the subject [OK]
Hint: Always put parentheses around the variable in when [OK]
Common Mistakes:
  • Omitting parentheses around the variable
  • Forgetting arrows after cases
  • Using when without braces
5. You want to use a when expression to categorize ages into groups: "Child" for 0-12, "Teen" for 13-19, "Adult" for 20-64, and "Senior" for 65 and above. Which when expression correctly implements this?
hard
A. when (age) { in 0..12 -> "Child" in 13..19 -> "Teen" in 20..64 -> "Adult" else -> "Senior" }
B. when { age >= 0 && age <= 12 -> "Child" age >= 13 && age <= 19 -> "Teen" age >= 20 && age <= 64 -> "Adult" age >= 65 -> "Senior" else -> "Unknown" }
C. when (age) { 0..12 -> "Child" 13..19 -> "Teen" 20..64 -> "Adult" 65 -> "Senior" }
D. when (age) { in 0..12 -> "Child" in 13..19 -> "Teen" in 20..64 -> "Adult" in 65..100 -> "Senior" else -> "Unknown" }

Solution

  1. Step 1: Understand when with condition checks

    when { age >= 0 && age <= 12 -> "Child" age >= 13 && age <= 19 -> "Teen" age >= 20 && age <= 64 -> "Adult" age >= 65 -> "Senior" else -> "Unknown" } uses when without argument and checks conditions with boolean expressions, which is valid and flexible.
  2. Step 2: Check other options for correctness

    when (age) { in 0..12 -> "Child" in 13..19 -> "Teen" in 20..64 -> "Adult" else -> "Senior" } is valid but misses handling negative ages explicitly; when (age) { 0..12 -> "Child" 13..19 -> "Teen" 20..64 -> "Adult" 65 -> "Senior" } uses invalid syntax for ranges; when (age) { in 0..12 -> "Child" in 13..19 -> "Teen" in 20..64 -> "Adult" in 65..100 -> "Senior" else -> "Unknown" } limits "Senior" to 65-100 and has an else for unknown ages.
  3. Step 3: Choose the best option

    when { age >= 0 && age <= 12 -> "Child" age >= 13 && age <= 19 -> "Teen" age >= 20 && age <= 64 -> "Adult" age >= 65 -> "Senior" else -> "Unknown" } covers all age ranges clearly with conditions and includes an else for unknown ages.
  4. Final Answer:

    when { age >= 0 && age <= 12 -> "Child" age >= 13 && age <= 19 -> "Teen" age >= 20 && age <= 64 -> "Adult" age >= 65 -> "Senior" else -> "Unknown" } -> Option B
  5. Quick Check:

    Use condition checks inside when for flexible ranges [OK]
Hint: Use condition checks inside when for complex ranges [OK]
Common Mistakes:
  • Using invalid range syntax without 'in'
  • Not handling unexpected values with else
  • Limiting ranges incorrectly or missing conditions
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