the art of java pattern matching

Abstract

Guarded patterns (JDK 19):

void shapeTester(Shape shape) {
  switch (shape) {
    // only works for patterns, no case "Foo" when somethingElse() -> ...
    case Triangle t when t.area() > 25 -> System.out.println("It's a big triangle");
    case Triangle t -> System.out.println("It's a small triangle");
    case Square s -> System.out.println("It's a small square");
    case Pentagon t -> System.out.println("It's a small pentagon");
    case Shape t -> System.out.println("It's a small shape");
  }
}

Patterns will be composable

public void printColor(Rectangle r) {
  if (r instanceof ColourRectangle(ColourPoint(Point p, Colour c), ColourPoint br)) {
    System.out.println(c);
  }
}