AnyCompiler

Sealed Classes

A sealed class restricts which classes can ever extend it — every subclass has to be known to the compiler at compile time, typically because they're declared in the same file. In exchange, the compiler can check a when expression over that type for exhaustiveness: if you handle every subclass, you don't need an else branch at all, and if a new subclass is ever added, every when that's missing a case for it becomes a compile error.

sealed class Shape
class Circle(val radius: Double) : Shape()
class Square(val side: Double) : Shape()

fun area(s: Shape): Double = when (s) {
    is Circle -> Math.PI * s.radius * s.radius
    is Square -> s.side * s.side
}

fun main() {
    println(area(Circle(2.0)))
    println(area(Square(3.0)))
}
Output
12.566370614359172
9.0

Compare this to the interfaces lesson's version of the same idea: an interface lets any class, anywhere, opt in — a sealed class instead gives the compiler a closed, fully-known set it can check exhaustively. Next: extension functions — adding a function to a type you didn't write.

Practice exercise

Define a sealed class Shape with subclasses Circle(radius) and Square(side). Write a fun area(s: Shape) using an exhaustive when, then print area(Square(5.0)).