Skip to content

Instantly share code, notes, and snippets.

@meowpunch
Last active January 13, 2022 08:17
Show Gist options
  • Save meowpunch/186223288c54f9eecfb65ee0228b3ab7 to your computer and use it in GitHub Desktop.
Save meowpunch/186223288c54f9eecfb65ee0228b3ab7 to your computer and use it in GitHub Desktop.
an example of JEP 405: Record Patterns & Array Patterns (Preview)
record Point(int x, int y) {}
enum Color { RED, GREEN, BLUE }
record ColoredPoint(Point p, Color c) {}
record Rectangle(ColoredPoint upperLeft, ColoredPoint lowerRight) {}
static void printXCoordOfUpperLeftPointBeforePatterns(Rectangle r) {
if (r == null) return;
ColoredPoint ul = r.upperLeft();
if (ul == null) return;
Point p = ul.p();
if (p == null) return;
int x = p.x();
System.out.println("Upper-left corner: " + x);
}
// with record patterns (future work)
static void printXCoordOfUpperLeftPointWithPatterns(Rectangle r) {
if (r instanceof Rectangle(ColoredPoint(Point(var x, var y), var c), var lr)) {
System.out.println("Upper-left corner: " + x);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment