What if you could replace messy if-else chains with one simple, powerful expression?
Why When with ranges and types in Kotlin? - Purpose & Use Cases
Imagine you have to check many different conditions on a number or an object type one by one using many if-else statements.
For example, checking if a number falls into certain ranges or if an object is of a certain type.
Writing many if-else statements is slow and confusing.
It's easy to make mistakes, miss a condition, or write repetitive code.
It becomes hard to read and maintain as the number of conditions grows.
The when expression in Kotlin lets you check multiple conditions clearly and concisely.
You can check ranges and types in one place, making your code easier to read and less error-prone.
if (x in 1..10) { println("Small number") } else if (x in 11..100) { println("Medium number") } else if (obj is String) { println("It's a string") }
when {
x in 1..10 -> println("Small number")
x in 11..100 -> println("Medium number")
obj is String -> println("It's a string")
}You can write clean, readable code that handles many conditions on values and types without clutter.
Checking user input: if a number is in a valid range or if the input is a specific type like String or Int, all in one simple structure.
Manual if-else chains are hard to read and error-prone.
when handles ranges and types clearly in one place.
It makes your code simpler, cleaner, and easier to maintain.
Practice
when expression in Kotlin do when used with ranges like in 1..5?Solution
Step 1: Understand the
The syntaxwhenwith range syntaxin 1..5insidewhenchecks if the value is between 1 and 5 inclusive.Step 2: Interpret the check
If the value is inside the range, the corresponding branch executes; otherwise, it moves to the next case.Final Answer:
It checks if the value falls within the specified range. -> Option DQuick Check:
whenwithinchecks range membership [OK]
in means inside the range [OK]- Thinking
increates a range instead of checking membership - Confusing
inwith assignment - Assuming it throws errors for out-of-range values
x is NOT in the range 10 to 20 using when in Kotlin?Solution
Step 1: Recall the correct negation syntax in
In Kotlin,when!inis used to check if a value is NOT in a range.Step 2: Match the syntax with options
when(x) { !in 10..20 -> "Outside" } uses!in 10..20correctly insidewhen. Other options use invalid keywords or syntax.Final Answer:
when(x) { !in 10..20 -> "Outside" } -> Option AQuick Check:
Use!into check exclusion from range [OK]
!in to say NOT in range [OK]- Using 'not in' instead of '!in'
- Writing variable name inside
whencase - Using undefined keywords like 'outside'
val x: Any = 42
val result = when (x) {
is Int -> "Integer"
in 1..10 -> "Small number"
else -> "Unknown"
}
println(result)Solution
Step 1: Check the type of
Variablexxis of typeAnybut holds the value 42, which is anInt.Step 2: Evaluate
The first branch checkswhenbranches in orderis Int, which is true, so it returns "Integer". The second branch is not checked because the first matched.Final Answer:
Integer -> Option CQuick Check:
whenmatches first true branch [OK]
is come before range checks [OK]- Assuming range check runs before type check
- Confusing value 42 as outside 1..10
- Thinking
whenchecks all branches
when expression:val y: Any = "Hello"
val output = when (y) {
in 1..5 -> "Number"
is String -> "Text"
else -> "Other"
}
println(output)Solution
Step 1: Analyze the
The variablein 1..5check onAnyyis of typeAny. Theinoperator with ranges requires a comparable type likeInt. Usingin 1..5onAnycauses a type mismatch error.Step 2: Check order of branches and syntax
Theis Stringcheck is valid but unreachable if the first branch errors. Also,whenin Kotlin does not requirebreak.Final Answer:
Cannot useinwithAnytype without casting -> Option AQuick Check:
Range checks need compatible types [OK]
in with ranges [OK]- Ignoring type mismatch for
inoperator - Thinking
whenneedsbreak - Assuming order of branches causes error
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?Solution
Step 1: Understand the conditions needed
We need to check ifvis anIntand then check its value range for "Small Int" or "Large Int". Also check ifvis aString.Step 2: Analyze each option's correctness
when (v) { in 1..10 -> "Small Int" is Int -> "Large Int" is String -> "String" else -> "Other" } incorrectly usesin 1..10without checking type first, causing errors ifvis notInt. when (v) { is Int in 1..10 -> "Small Int" is Int -> "Large Int" is String -> "String" else -> "Other" } uses invalid syntaxis 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 syntaxis Int && v in 1..10insidewhen. 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 anifinside the branch to distinguish ranges.Final Answer:
Option B correctly implements the logic. -> Option BQuick Check:
Use nestedifinsidewhenfor complex conditions [OK]
- Using invalid syntax combining
isandin - Not checking type before range
- Trying to use logical operators directly in
whencases
Ready to prove it?
Pass the test and this pattern moves unknown
