0
0
Kotlinprogramming~5 mins

Sealed classes with when exhaustive check in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Sealed classes with when exhaustive check
O(n)
Understanding Time Complexity

We want to understand how the time it takes to run code with sealed classes and when expressions changes as the input grows.

Specifically, how does checking all cases in a sealed class with a when expression affect performance?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

sealed class Result {
    data class Success(val data: String) : Result()
    object Loading : Result()
    data class Error(val message: String) : Result()
}

fun handleResult(result: Result) {
    when (result) {
        is Result.Success -> println("Data: ${result.data}")
        Result.Loading -> println("Loading...")
        is Result.Error -> println("Error: ${result.message}")
    }
}

This code defines a sealed class with three types and uses a when expression to handle each type exhaustively.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The when expression checks the type of the input once.
  • How many times: Exactly one time per call to handleResult.
How Execution Grows With Input

Each time we call handleResult, it checks the input's type once. The number of checks does not increase with input size.

Input Size (n)Approx. Operations
1010 type checks
100100 type checks
10001000 type checks

Pattern observation: The operations grow linearly with the number of calls, but each call does a fixed small number of checks.

Final Time Complexity

Time Complexity: O(n)

This means the total time grows directly with how many times you call the function, but each call is very fast and constant time.

Common Mistake

[X] Wrong: "The when expression with sealed classes does a lot of work checking all cases every time, so it's slow."

[OK] Correct: The when expression checks only the actual type of the input once per call, not all cases. It's efficient because sealed classes let the compiler know all possible types.

Interview Connect

Understanding how sealed classes and when expressions work helps you write clear and efficient Kotlin code. It shows you can reason about how your code runs as it handles different cases.

Self-Check

What if the sealed class had 100 different subclasses? How would that affect the time complexity of the when expression?