|
| 1 | +/** |
| 2 | + * To run: `java --enable-preview --source 20 RecordsPatternSecondPreviewTest.java` |
| 3 | + */ |
| 4 | +public class RecordPatternsSecondPreviewTest { |
| 5 | + public static void main(String[] args) { |
| 6 | + enhancedForLoop(); |
| 7 | + } |
| 8 | + |
| 9 | + public static void enhancedForLoop() { |
| 10 | + var points = new Point[] { |
| 11 | + new Point(10, 10), |
| 12 | + new Point(20, 20), |
| 13 | + new Point(30, 30), |
| 14 | + new Point(20, 50), |
| 15 | + new Point(10, 60) |
| 16 | + }; |
| 17 | + |
| 18 | + // we can now deconstruct a record type in the enhanced for loop |
| 19 | + for (Point(int x, int y) : points) { |
| 20 | + System.out.print("Drawing at x=%d and y=%d", x, y); |
| 21 | + } |
| 22 | + } |
| 23 | + |
| 24 | + public static void genericInferrenceTest() { |
| 25 | + var point = new Point(42, 42); |
| 26 | + var decoratedPoint = new Decorator(new ColoredPoint(point, "RED")); |
| 27 | + var anotherDecorated = new Decorator(decoratedPoint); |
| 28 | + |
| 29 | + // here we don't need to use `Decorator<Decorator<ColoredPoint>>(Decorator<ColoredPoint>(ColoredPoint cp))` like in JDK 19 |
| 30 | + if (anotherDecorated instanceof Decorator(Decorator(ColoredPoint(Point(int x, int y), String color)))) { |
| 31 | + System.out.println("Aren't you using too much decorator?"); |
| 32 | + System.out.printf("x=%d, y=%d; color=%s", x, y, color); |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + static void invalidGenericEnhancedForLoop() { |
| 37 | + var items = new Decorator<Object>[] { new Object() }; |
| 38 | + |
| 39 | + // the pattern is not exhaustive (should be Decorator<Object>) |
| 40 | + // for (Decorator<String> d : items) { |
| 41 | + // } |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +record Point(int x, int y) {} |
| 46 | + |
| 47 | +record ColoredPoint(Point p, String color) {} |
| 48 | + |
| 49 | +record Decorator<T>(T t) {} |
| 50 | + |
0 commit comments