Throw as an expression in Kotlin - Time & Space Complexity
We want to understand how the time cost changes when using "throw" as an expression in Kotlin.
Specifically, how does this affect the number of steps the program takes as input grows?
Analyze the time complexity of the following code snippet.
fun getValueOrThrow(map: Map, key: String): Int =
map[key] ?: throw IllegalArgumentException("Key not found")
fun processKeys(map: Map, keys: List) {
for (key in keys) {
val value = getValueOrThrow(map, key)
println(value)
}
}
This code tries to get values from a map for each key in a list, throwing an exception if a key is missing.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping over the list of keys and accessing the map for each key.
- How many times: Once for each key in the list (n times).
Each key in the list causes one map lookup and possibly a throw if missing.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 map lookups and checks |
| 100 | About 100 map lookups and checks |
| 1000 | About 1000 map lookups and checks |
Pattern observation: The number of operations grows directly with the number of keys.
Time Complexity: O(n)
This means the time grows linearly with the number of keys processed.
[X] Wrong: "Using throw as an expression makes the code slower for all cases."
[OK] Correct: Throwing an exception only happens when a key is missing, which is rare or input-dependent. The normal map lookup still runs in expected constant time, so the main cost grows linearly with input size.
Understanding how exceptions affect time helps you explain your code's behavior clearly and shows you think about performance in real situations.
What if we replaced the map lookup with a more complex search, like scanning a list? How would the time complexity change?