Result type for functional error handling in Kotlin - Time & Space Complexity
When using the Result type for error handling, it is important to understand how the time to process results grows as input changes.
We want to know how the cost of handling success or failure scales with the number of operations.
Analyze the time complexity of the following Kotlin code using Result type.
fun processList(items: List): Result> {
return items.map { item ->
if (item >= 0) Result.success(item * 2)
else Result.failure(Exception("Negative value"))
}.let { results ->
if (results.any { it.isFailure }) Result.failure(Exception("Contains failure"))
else Result.success(results.map { it.getOrThrow() })
}
}
This code processes a list of integers, doubling each if non-negative, and collects results using the Result type to handle errors.
Look for loops or repeated actions in the code.
- Primary operation: Mapping over the list twice (once to create Result objects, once to extract values).
- How many times: Each map runs once over all items, so twice over the list size.
As the list size grows, the number of operations grows proportionally.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 20 (2 passes x 10 items) |
| 100 | About 200 (2 passes x 100 items) |
| 1000 | About 2000 (2 passes x 1000 items) |
Pattern observation: The operations grow linearly with the input size, doubling due to two passes.
Time Complexity: O(n)
This means the time to process results grows in direct proportion to the number of items.
[X] Wrong: "Using Result type adds extra loops that make the code slower than linear."
[OK] Correct: Even with multiple passes, the total work still grows linearly with input size, so it remains efficient.
Understanding how error handling affects performance helps you write clear and efficient Kotlin code, a skill valued in many coding challenges and real projects.
"What if we combined the two map operations into one? How would the time complexity change?"