Sealed classes with when exhaustive check in Kotlin - Time & Space 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?
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 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.
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 |
|---|---|
| 10 | 10 type checks |
| 100 | 100 type checks |
| 1000 | 1000 type checks |
Pattern observation: The operations grow linearly with the number of calls, but each call does a fixed small number of checks.
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.
[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.
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.
What if the sealed class had 100 different subclasses? How would that affect the time complexity of the when expression?