google / google-java-format

Reformats Java source code to comply with Google Java Style.
Other
5.58k stars 855 forks source link

Pattern Matching for Record compatibility issue #1125

Closed Goooler closed 2 months ago

Goooler commented 2 months ago
public class Java21Example {
    record Point(int x, int y) {}

    public static int recordPattern(Object obj) {
        if(obj instanceof Point(int x, int y)) {
            return x+y;
        }
        return 0;
    }
}

Using GJF 1.23.0 and run google-java-format src/main/java/com/shutch/spotless/Java21Example.java we can see an error:

src/main/java/com/shutch/spotless/Java21Example.java:8:33: error: ')' expected
src/main/java/com/shutch/spotless/Java21Example.java:8:47: error: -> expected

You can repro this in https://github.com/sihutch/spotless-toolchains.

cushon commented 2 months ago

The formatter needs to be running on JDK 21 or newer to format Java 21 features.

$ java -version
openjdk version "21.0.4" 2024-07-16 LTS
$ java -jar google-java-format-1.23.0-all-deps.jar Java21Example.java
public class Java21Example {
  record Point(int x, int y) {}

  public static int recordPattern(Object obj) {
    if (obj instanceof Point(int x, int y)) {
      return x + y;
    }
    return 0;
  }
}
Goooler commented 2 months ago

Oooops, I missed switching my local Java version. Thanks!