21 lines
954 B
Java
21 lines
954 B
Java
/** JEP 440 (final): deconstruct records in instanceof and switch, nested. */
|
|
public class RecordPatternsDemo {
|
|
record Point(int x, int y) {}
|
|
record Line(Point from, Point to) {}
|
|
record Box<T>(T content) {}
|
|
|
|
static String describe(Object o) {
|
|
if (o instanceof Line(Point(var x1, var y1), Point(var x2, var y2)))
|
|
return "line from (" + x1 + "," + y1 + ") to (" + x2 + "," + y2 + ") length^2=" + ((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
|
|
if (o instanceof Box<?>(String s)) return "box of String " + s;
|
|
if (o instanceof Box<?>(Integer i)) return "box of Integer " + i;
|
|
return "no match";
|
|
}
|
|
public static void main(String[] args) {
|
|
System.out.println(describe(new Line(new Point(0, 0), new Point(3, 4))));
|
|
System.out.println(describe(new Box<>("hi")));
|
|
System.out.println(describe(new Box<>(7)));
|
|
System.out.println(describe(new Box<>(2.5)));
|
|
}
|
|
}
|