Not exhaustive pattern matching in Java. When it should be

1 day ago 1
ARTICLE AD BOX

In Java, a sealed class is not implicitly abstract1. Which means your hierarchy allows Shape and Quadrangle instances that are not one of Rectangle, Diamond, or Circle. Thus, your switch is not exhaustive.

There are at least three solutions. I suspect the first one would fit your scenario best and is the one you're looking for.

1. Make Shape and Quadrangle abstract (whether abstract class or interface)
abstract sealed class Shape permits Quadrangle, Circle {} abstract sealed class Quadrangle permits Rectangle, Diamond {}
2. Add cases for Shape and Quadrangle to the switch
switch (shape) { case Rectangle _ -> {} case Diamond _ -> {} case Circle _ -> {} // Must put least specific types last case Quadrangle _ -> {} case Shape _ -> {} }
3. Add a default case to the switch
switch (shape) { case Rectangle _ -> {} case Diamond _ -> {} case Circle _ -> {} default -> {} }

1. In other languages, such as Kotlin, a sealed class is implicitly abstract. This may be the source of your confusion.

Read Entire Article