When as expression returning value in Kotlin - Time & Space Complexity
We want to understand how the time taken by a Kotlin when expression changes as the input changes.
Specifically, how does the number of checks grow when using when to return a value?
Analyze the time complexity of the following code snippet.
fun getDayType(day: Int): String = when(day) {
1 -> "Monday"
2 -> "Tuesday"
3 -> "Wednesday"
4 -> "Thursday"
5 -> "Friday"
6 -> "Saturday"
7 -> "Sunday"
else -> "Invalid day"
}
This code returns the name of the day for a given number using when as an expression.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Checking each case in the
whenexpression. - How many times: Up to 7 checks in the worst case before matching or hitting
else.
As the input number changes, the when expression checks cases one by one until it finds a match.
| Input Size (n) | Approx. Operations |
|---|---|
| 3 | 3 checks |
| 5 | 5 checks |
| 7 | 7 checks |
Pattern observation: The number of checks grows linearly with the number of cases.
Time Complexity: O(n)
This means the time to find the matching case grows in a straight line as the number of cases increases.
[X] Wrong: "The when expression always runs in constant time no matter how many cases it has."
[OK] Correct: Actually, the when expression checks cases one by one until it finds a match, so more cases mean more checks and longer time.
Understanding how when expressions scale helps you explain how your code behaves with more conditions, showing you think about efficiency clearly.
"What if we replaced the when expression with a map lookup? How would the time complexity change?"
Practice
when expression in Kotlin return when used as an expression?Solution
Step 1: Understand
In Kotlin,whenas expressionwhencan be used as an expression that returns a value depending on which case matches.Step 2: Compare with other options
It does not always return Unit, nor a Boolean, and it requires anelsebranch to avoid exceptions, so it won't throw by default.Final Answer:
It returns a value based on the matched case. -> Option AQuick Check:
whenreturns value [OK]
when returns the matched case value [OK]- Thinking
whenalways returns Unit - Confusing
whenwithifreturning Boolean - Forgetting to add an
elsebranch
when as an expression returning a value in Kotlin?Solution
Step 1: Check correct
val result = when (x) { in 1..10 -> "Small"; else -> "Large" } useswhensyntax with argumentwhen (x)with cases separated by semicolons and anelsebranch, which is correct.Step 2: Identify syntax errors in other options
val result = when { x > 0 -> "Positive"; else -> "Non-positive" } uses semicolons inside braces correctly; val result = when (x) { x > 0 -> "Positive" else -> "Non-positive" } misses semicolon beforeelse; val result = when x { 1 -> "One"; else -> "Other" } misses parentheses aroundx.Final Answer:
val result = when (x) { in 1..10 -> "Small"; else -> "Large" } -> Option DQuick Check:
Correctwhensyntax uses parentheses and semicolons [OK]
- Omitting parentheses around the variable
- Using commas instead of semicolons
- Missing semicolon before else branch
val x = 5
val result = when {
x < 0 -> "Negative"
x == 0 -> "Zero"
x in 1..10 -> "Small"
else -> "Large"
}
println(result)Solution
Step 1: Evaluate conditions in order
x = 5 is not less than 0, not equal to 0, but is in 1..10 range, so the third case matches.Step 2: Determine returned value
The matched case returns "Small", soresultis "Small".Final Answer:
Small -> Option AQuick Check:
5 in 1..10 = true, returns "Small" [OK]
- Assuming else branch runs for 5
- Confusing equality and range checks
- Ignoring order of conditions
when as an expression:val x = 3
val result = when (x) {
1 -> "One"
2 -> "Two"
}
println(result)Solution
Step 1: Check completeness of
Thewhenexpressionwhenexpression covers only 1 and 2, but x = 3 is not handled and noelsebranch is provided.Step 2: Understand Kotlin requirement for exhaustive
When used as an expression,whenwhenmust be exhaustive, so missingelsecauses a compilation error.Final Answer:
Missingelsebranch causes compilation error. -> Option BQuick Check:
Exhaustivewhenneedselse[OK]
else if not all cases covered [OK]- Ignoring missing
elsebranch - Thinking semicolons are mandatory
- Assuming
whenalways compiles without else
when as an expression. Which code correctly returns "A" for scores 90 and above, "B" for 80-89, "C" for 70-79, and "F" otherwise?Solution
Step 1: Understand
val grade = when { score >= 90 -> "A" score >= 80 -> "B" score >= 70 -> "C" else -> "F" } useswhenwith condition expressionswhenwithout argument and conditions likescore >= 90, which is valid and clear for ranges.Step 2: Check other options for errors
val grade = when (score) { in 90..100 -> "A" in 80..89 -> "B" in 70..79 -> "C" else -> "F" } is correct syntax but uses ranges; val grade = when (score) { score >= 90 -> "A" score >= 80 -> "B" score >= 70 -> "C" else -> "F" } incorrectly uses conditions insidewhen(score)which expects values, not conditions; val grade = when { in 90..100 -> "A" in 80..89 -> "B" in 70..79 -> "C" else -> "F" } usesinwithout variable, which is invalid.Final Answer:
val grade = when { score >= 90 -> "A" score >= 80 -> "B" score >= 70 -> "C" else -> "F" } -> Option CQuick Check:
Usewhenwithout argument for conditions [OK]
when without argument for condition checks [OK]- Using conditions inside
when(variable) - Omitting variable in range checks
- Misplacing
inkeyword
Ready to prove it?
Pass the test and this pattern moves unknown
