0Pricing
Java Academy · Lesson

Exhaustive switch on Sealed

Compile-time completeness.

Exhaustive switch

When you switch over a sealed type, the compiler knows every permitted subtype. If your switch covers them all, it is exhaustive and you do not need a default branch.

A Type Pattern switch

Switch expressions can match on the runtime type of a sealed value using type patterns.

public class Main {
    sealed interface Shape permits Circle, Square {}
    record Circle(double radius) implements Shape {}
    record Square(double side) implements Shape {}

    static String describe(Shape s) {
        return switch (s) {
            case Circle c -> "circle r=" + c.radius();
            case Square sq -> "square s=" + sq.side();
        };
    }

    public static void main(String[] args) {
        System.out.println(describe(new Circle(2)));
        System.out.println(describe(new Square(3)));
    }
}

All lessons in this course

  1. Declaring Sealed Types
  2. permits Clause
  3. Sealed with Records
  4. Exhaustive switch on Sealed
← Back to Java Academy