0
0
Kotlinprogramming~5 mins

Result type for functional error handling in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Result type for functional error handling
O(n)
Understanding Time 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.

Scenario Under Consideration

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.

Identify Repeating Operations

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.
How Execution Grows With Input

As the list size grows, the number of operations grows proportionally.

Input Size (n)Approx. Operations
10About 20 (2 passes x 10 items)
100About 200 (2 passes x 100 items)
1000About 2000 (2 passes x 1000 items)

Pattern observation: The operations grow linearly with the input size, doubling due to two passes.

Final Time Complexity

Time Complexity: O(n)

This means the time to process results grows in direct proportion to the number of items.

Common Mistake

[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.

Interview Connect

Understanding how error handling affects performance helps you write clear and efficient Kotlin code, a skill valued in many coding challenges and real projects.

Self-Check

"What if we combined the two map operations into one? How would the time complexity change?"