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?
Practice
sealed classes in Kotlin when combined with a when expression?Solution
Step 1: Understand sealed classes restriction
Sealed classes restrict subclassing to the same file, so all subclasses are known at compile time.Step 2: Effect on when expression
This allows thewhenexpression to be exhaustive because the compiler knows all possible subclasses.Final Answer:
Thewhenexpression becomes exhaustive, ensuring all cases are handled. -> Option AQuick Check:
Sealed classes + when = exhaustive check [OK]
- Thinking sealed classes allow subclassing anywhere
- Confusing sealed classes with data classes
- Believing sealed classes auto-generate methods
Solution
Step 1: Recall sealed class declaration syntax
In Kotlin, sealed classes are declared with the keywordsealedfollowed byclassand the class name.Step 2: Check options for correctness
sealed class Shape {} uses correct syntax:sealed class Shape {}. open sealed class Shape {} incorrectly addsopen, which is not allowed. sealed interface Shape {} usessealed interface, which is invalid. final sealed class Shape {} usesfinal sealed class, which is not allowed.Final Answer:
sealed class Shape {} -> Option AQuick Check:
sealed class declaration = sealed class Shape {} [OK]
- Adding 'open' modifier to sealed class
- Trying to declare sealed interfaces (not allowed)
- Using 'final' modifier with sealed class
describe function when called with Shape.Circle(5.0)?
sealed class Shape {
data class Circle(val radius: Double) : Shape()
data class Rectangle(val width: Double, val height: Double) : Shape()
}
fun describe(shape: Shape): String = when(shape) {
is Shape.Circle -> "Circle with radius ${shape.radius}"
is Shape.Rectangle -> "Rectangle with width ${shape.width} and height ${shape.height}"
}Solution
Step 1: Identify the input and matching when branch
The input isShape.Circle(5.0). Thewhenexpression matchesis Shape.Circlebranch.Step 2: Evaluate the returned string
The branch returns the string "Circle with radius 5.0" using the radius property.Final Answer:
Circle with radius 5.0 -> Option DQuick Check:
Input Circle(5.0) returns "Circle with radius 5.0" [OK]
- Confusing Circle with Rectangle output
- Expecting a compilation error due to else missing
- Returning class name instead of formatted string
sealed class Result {
object Success : Result()
object Failure : Result()
}
fun handle(result: Result) = when(result) {
is Result.Success -> "Success"
}Solution
Step 1: Identify the sealed class subclasses
Result has two subclasses: Success and Failure.Step 2: Check when expression branches
The when expression only handles Result.Success, missing Result.Failure branch.Step 3: Understand Kotlin's exhaustiveness check
Since Result is sealed, when must handle all subclasses or have an else branch. Missing Failure causes compilation error.Final Answer:
Compilation error: when expression is not exhaustive; add branch for Result.Failure. -> Option BQuick Check:
Sealed class when must cover all subclasses [OK]
- Assuming runtime error instead of compile error
- Ignoring missing branches in when
- Thinking sealed classes can't have object subclasses
Operation with subclasses Add, Subtract, and Multiply. Write a Kotlin function calculate that takes an Operation and two integers, and returns the result of applying the operation. Which of the following implementations correctly uses an exhaustive when expression?Solution
Step 1: Check all subclasses handled in when
Operation has Add, Subtract, Multiply. fun calculate(op: Operation, a: Int, b: Int): Int = when(op) { is Operation.Add -> a + b is Operation.Subtract -> a - b is Operation.Multiply -> a * b } handles all three explicitly.Step 2: Verify exhaustiveness and correctness
fun calculate(op: Operation, a: Int, b: Int): Int = when(op) { is Operation.Add -> a + b is Operation.Subtract -> a - b is Operation.Multiply -> a * b } covers all subclasses, so when is exhaustive. The other options miss some subclasses or rely on else, which is less clear.Final Answer:
fun calculate(op: Operation, a: Int, b: Int): Int = when(op) { is Operation.Add -> a + b is Operation.Subtract -> a - b is Operation.Multiply -> a * b } -> Option CQuick Check:
All subclasses covered in when = exhaustive [OK]
- Missing some subclasses in when branches
- Using else instead of explicit branches
- Returning wrong default values
Ready to prove it?
Pass the test and this pattern moves unknown
