What if you could replace long, confusing if-else chains with a simple, elegant expression that does it all?
Why When expression as powerful switch in Kotlin? - Purpose & Use Cases
Imagine you have a list of tasks, and you want to perform different actions based on the type of each task. Doing this manually means writing many if-else statements, checking each condition one by one.
Using many if-else statements is slow to write and hard to read. It's easy to make mistakes, like missing a case or repeating code. When you want to add new cases, you have to change many places, which can cause bugs.
The when expression in Kotlin acts like a powerful switch. It lets you check many conditions clearly and concisely in one place. It's easier to read, less error-prone, and you can return values directly from it.
if (x == 1) { println("One") } else if (x == 2) { println("Two") } else { println("Other") }
when (x) {
1 -> println("One")
2 -> println("Two")
else -> println("Other")
}It enables writing clear, concise, and maintainable code that handles many conditions elegantly in one place.
Think of a vending machine that gives different snacks based on the button pressed. Using when, you can easily map buttons to snacks without messy if-else chains.
Manual if-else chains are hard to read and maintain.
When expression simplifies multiple condition checks.
It makes your code cleaner, safer, and easier to update.
Practice
when expression in Kotlin?Solution
Step 1: Understand the role of
Thewhenwhenexpression is used to choose between different actions depending on the value it checks.Step 2: Compare with other options
The other options describe loops, functions, and variables, which are unrelated towhen.Final Answer:
To select actions based on different values, like a switch statement -> Option CQuick Check:
whenchooses actions by value [OK]
when as a smarter switch [OK]- Confusing
whenwith loops - Thinking
whendeclares variables - Mixing
whenwith function definitions
when expression in Kotlin?Solution
Step 1: Identify Kotlin
The correct syntax useswhensyntaxwhen (x) { value -> action }with arrows and braces.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.Final Answer:
when (x) { 1 -> println("One") 2 -> println("Two") else -> println("Other") } -> Option DQuick Check:
Kotlinwhenuses arrows and braces [OK]
when [OK]- Using colon (:) instead of arrow (->)
- Confusing
whenwith switch syntax - Omitting parentheses around the variable
val x = 3
when (x) {
1, 2 -> println("Small")
in 3..5 -> println("Medium")
else -> println("Large")
}Solution
Step 1: Check the value of
The variablexxis 3.Step 2: Match
3 is not in 1 or 2, but it is in the range 3..5, so "Medium" is printed.xwithwhencasesFinal Answer:
Medium -> Option AQuick Check:
3 in 3..5 means output is "Medium" [OK]
- Ignoring ranges and picking wrong case
- Assuming 3 matches 1 or 2
- Thinking else runs when a range matches
when expression:val y = 10
when y {
5 -> println("Five")
10 -> println("Ten")
else -> println("Other")
}Solution
Step 1: Check
Thewhensyntaxwhenexpression requires parentheses around the variable:when (y).Step 2: Check other syntax parts
Braces are present. Arrows (->) are correctly used after all cases includingelse. The syntax error is missing parentheses aroundy.Final Answer:
Missing parentheses aroundyinwhen-> Option AQuick Check:
whenneeds parentheses around the subject [OK]
when [OK]- Omitting parentheses around the variable
- Forgetting arrows after cases
- Using
whenwithout braces
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?Solution
Step 1: Understand
when { age >= 0 && age <= 12 -> "Child" age >= 13 && age <= 19 -> "Teen" age >= 20 && age <= 64 -> "Adult" age >= 65 -> "Senior" else -> "Unknown" } useswhenwith condition checkswhenwithout argument and checks conditions with boolean expressions, which is valid and flexible.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.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.Final Answer:
when { age >= 0 && age <= 12 -> "Child" age >= 13 && age <= 19 -> "Teen" age >= 20 && age <= 64 -> "Adult" age >= 65 -> "Senior" else -> "Unknown" } -> Option BQuick Check:
Use condition checks insidewhenfor flexible ranges [OK]
when for complex ranges [OK]- Using invalid range syntax without 'in'
- Not handling unexpected values with else
- Limiting ranges incorrectly or missing conditions
Ready to prove it?
Pass the test and this pattern moves unknown
