13

Assume the structure:

sealed class Shape permits Circle, Quadrangle {}

sealed class Quadrangle extends Shape permits Diamond, Rectangle { }
final class Rectangle extends Quadrangle {}
final class Diamond extends Quadrangle {}
final class Circle extends Shape {}

Then when I have e.g. such switch statement:

switch (shape) {
    case Rectangle _-> System.out.println("");
    case Diamond _-> System.out.println("");
    case Circle _-> System.out.println("");
}

I have information about not covering all cases and forced to implement default. In my opinion this is some bug or something. It should not be that way. As I cover all cases. Is there a way to achieve the exhaustiveness of the switch statement and if yes then how?

0

1 Answer 1

20

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.