record Point(int x, int y) { }
record Line(Point from, Point to) { }
Object shape = new Line(new Point(0, 0), new Point(3, 4));
// *** before: ***
String text1 = "?";
if (shape instanceof Line) {
Line line = (Line) shape; // unpacking by hand, step by step
Point a = line.from();
Point b = line.to();
text1 = "from " + a.x() + "," + a.y() + " to " + b.x() + "," + b.y();
}
// *** in version 21: ***
String text2 = switch (shape) {
case Line(Point(var x1, var y1), Point(var x2, var y2)) ->
"from " + x1 + "," + y1 + " to " + x2 + "," + y2;
case Point(int x, int y) -> "point " + x + "," + y;
default -> "?";
};
if (shape instanceof Line(Point from, Point to)) { // works in instanceof too
System.out.println(from + " " + to);
}
System.out.println(text1);
System.out.println(text2);