Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8296802

Parse errors when deconstructing a record using the enhanced for loop of JEP 432

XMLWordPrintable

    • Icon: Bug Bug
    • Resolution: Fixed
    • Icon: P4 P4
    • 20
    • None
    • tools
    • None
    • b27

      1. Reported error about JEP 432's enhanced for loop, when deconstructing a record with primitive components.

      public class RecordPatternTest {
          public static void main(String argv[]) {
              Point[] pointArray = {new Point(1,2), new Point(3,4)};
              dump(pointArray);
          }

          record Point(int x, int y) {}

          static void dump(Point[] pointArray) {
              for (Point(int x, int y) : pointArray) {
                  System.out.println("(" + x + ", " + y + ")");
              }
          }
      }

      $ java --enable-preview --source 20 RecordPatternTest.java

      RecordPatternTest.java:10: error: '.class' expected

              for (Point(int x, int y) : pointArray) {
                             ^
      RecordPatternTest.java:10: error: ';' expected
              for (Point(int x, int y) : pointArray) {
                              ^
      RecordPatternTest.java:10: error: '.class' expected
              for (Point(int x, int y) : pointArray) {
                                    ^
      RecordPatternTest.java:10: error: not a statement
              for (Point(int x, int y) : pointArray) {
                                ^
      RecordPatternTest.java:10: error: ';' expected

              for (Point(int x, int y) : pointArray) {
                                     ^
      RecordPatternTest.java:10: error: not a statement
              for (Point(int x, int y) : pointArray) {
                                         ^
      RecordPatternTest.java:10: error: ';' expected
              for (Point(int x, int y) : pointArray) {
                                                   ^
      7 errors
      error: compilation failed
       
      However, if we use “var” instead of “int”, i.e.
      for (Point(var x, var y) : pointArray) {
      then it works:
       
      $ java --enable-preview --source 20 RecordPatternTest.java
      Note: RecordPatternTest.java uses preview features of Java SE 20.
      Note: Recompile with -Xlint:preview for details.
      (1, 2)
      (3, 4)

      2. Nested patterns raise parsing error
      3. Lambdas in normal for erroneously parsed as patterns:

      static <T> void method2(Function<Integer, Integer> f) {}
      int i = 42;
      for (method2((Integer a) -> 42); i == 0;) { i++; }

            abimpoudis Angelos Bimpoudis
            abimpoudis Angelos Bimpoudis
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated:
              Resolved: