0
0
Kotlinprogramming~5 mins

Sealed classes for restricted hierarchies in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Sealed classes for restricted hierarchies
O(1)
Understanding Time Complexity

We want to understand how the time it takes to work with sealed classes changes as we add more subclasses or data.

How does the program's work grow when using sealed classes in Kotlin?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

sealed class Shape {
    data class Circle(val radius: Double) : Shape()
    data class Rectangle(val width: Double, val height: Double) : Shape()
    object NotAShape : Shape()
}

fun area(shape: Shape): Double = when(shape) {
    is Shape.Circle -> Math.PI * shape.radius * shape.radius
    is Shape.Rectangle -> shape.width * shape.height
    Shape.NotAShape -> 0.0
}

This code defines a sealed class with a few subclasses and a function that calculates area based on the shape type.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The when expression checks the type of the shape once.
  • How many times: Exactly once per call to area, no loops or recursion inside.
How Execution Grows With Input

Since the function checks the shape type once, the work stays the same no matter how many subclasses exist.

Input Size (n)Approx. Operations
11 check
101 check
1001 check

Pattern observation: The time to compute area does not grow with the number of subclasses because the check is direct and fixed.

Final Time Complexity

Time Complexity: O(1)

This means the time to find the area stays constant no matter how many subclasses the sealed class has.

Common Mistake

[X] Wrong: "Adding more subclasses to a sealed class makes the area function slower because it has to check all of them."

[OK] Correct: The when expression is compiled to a direct check, so it does not loop through subclasses but jumps directly to the right case.

Interview Connect

Understanding how sealed classes work helps you explain how Kotlin handles restricted hierarchies efficiently, showing you know both design and performance.

Self-Check

"What if the area function used a list of shapes and calculated the total area by looping through them? How would the time complexity change?"