Finally block behavior in Kotlin - Time & Space Complexity
We want to understand how the time taken by a Kotlin program changes when it uses a finally block.
Specifically, we ask: does adding a finally block change how long the program runs as input grows?
Analyze the time complexity of the following code snippet.
fun processList(items: List<Int>) {
try {
for (item in items) {
println(item)
}
} finally {
println("Done processing")
}
}
This code prints each item in a list, then always prints "Done processing" at the end.
- Primary operation: The
forloop that prints each item in the list. - How many times: Once for each item in the list (n times).
- Finally block: Runs exactly once after the loop finishes.
The loop runs once per item, so if the list has more items, the time grows proportionally.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 prints + 1 finally print |
| 100 | About 100 prints + 1 finally print |
| 1000 | About 1000 prints + 1 finally print |
Pattern observation: The time grows roughly in a straight line with the number of items. The finally block adds a fixed small cost.
Time Complexity: O(n)
This means the time grows directly with the number of items; the finally block does not change this growth.
[X] Wrong: "The finally block runs multiple times and makes the program slower as the list grows."
[OK] Correct: The finally block runs only once after the loop, so it adds a fixed cost, not one per item.
Understanding how finally blocks behave helps you explain program flow clearly and reason about performance in real code.
What if the finally block contained a loop over the same list? How would the time complexity change?