Pattern matching, not informative error message when the binding name is missing

Remi Forax forax at univ-mlv.fr
Mon Jun 7 09:03:02 UTC 2021


Hi all,
with this code

  sealed interface Vehicle {}
  record Car(String owner, String color) implements Vehicle {}
  record Bus(String owner) implements Vehicle {}

  public static void example3() {
    var vehicles = List.of(
        new Car("Bob", "red"),
        new Bus("Ana")
    );
    var tax = vehicles.stream()
        .mapToInt(v -> switch(v) {
            case Car -> 100;
            case Bus -> 200;
            default -> throw new AssertionError();
        }).sum();
    System.out.println("tax " + tax);
  }

If there is no binding name in the case,
  case Car
instead of
  case Car car
the error message is not very explicit

PatternMatching101.java:40: error: cannot find symbol
                 case Car -> 100;
                      ^
  symbol:   variable Car
  location: class PatternMatching101

I believe that in this case, it's possible to know that this is a switch on types, so provide a better error message.

regards,
Rémi


More information about the core-libs-dev mailing list