Pattern matching for switch (Java 21)
MediumSince Java 21, a case can test a type and bind it: case Circle c ->. Add a guard with when, take records apart with record patterns, and handle null with case null. Over a sealed type the compiler checks every subtype is covered, so no default is needed.
sealed interface Shape permits Circle, Rect, Square {}
record Circle(double r) implements Shape {}
record Rect(double w, double h) implements Shape {}
record Square(double side) implements Shape {}
static String describe(Shape s) {
return switch (s) {
case null -> "nothing";
…