0
0
Kotlinprogramming~3 mins

Why Sealed classes for restricted hierarchies in Kotlin? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your program could warn you when you forget to handle a case? Sealed classes make that happen!

The Scenario

Imagine you have a set of related types, like different shapes: Circle, Square, and Triangle. You want to handle each shape differently in your code. Without a clear way to restrict which shapes exist, you might accidentally add unsupported shapes or forget to handle some cases.

The Problem

Manually managing all possible types is slow and error-prone. You might miss a shape when writing code, causing bugs. Also, adding new shapes anywhere in the code can break existing logic without warning. This makes your program fragile and hard to maintain.

The Solution

Sealed classes let you define a fixed set of subclasses in one place. This means the compiler knows all possible types and can help you check that you handle every case. It prevents unexpected types from sneaking in, making your code safer and easier to understand.

Before vs After
Before
open class Shape
class Circle : Shape()
class Square : Shape()
// Someone adds Hexagon later

fun draw(shape: Shape) {
  if (shape is Circle) { /*...*/ }
  else if (shape is Square) { /*...*/ }
  // No check for Hexagon!
}
After
sealed class Shape {
  class Circle : Shape()
  class Square : Shape()
}

fun draw(shape: Shape) = when(shape) {
  is Shape.Circle -> { /*...*/ }
  is Shape.Square -> { /*...*/ }
  // Compiler warns if a case is missing
}
What It Enables

It enables safer and clearer code by restricting and controlling all possible types in a hierarchy.

Real Life Example

Think of a traffic light system with fixed states: Red, Yellow, Green. Using sealed classes ensures you only have these states and handle each one properly, avoiding unexpected errors.

Key Takeaways

Sealed classes restrict which subclasses can exist.

This helps the compiler check all cases are handled.

It makes your code safer, clearer, and easier to maintain.