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?"