google / google-java-format

Reformats Java source code to comply with Google Java Style.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Formatter fails when `default` is part of switch expression

nastra opened this issue · comments

switch (reference.getReferenceTypeCase()) {
  case A -> ...
  case B, default -> throw new IllegalArgumentException("Unhandled");
}

will fail with

Caused by: com.google.googlejavaformat.java.FormatterException: 65:13: error: expected token: 'default'; generated - instead
                    at com.google.googlejavaformat.java.Formatter.getFormatReplacements(Formatter.java:273)
                    at com.google.googlejavaformat.java.Formatter.formatSource(Formatter.java:247)
                    at com.google.googlejavaformat.java.Formatter.formatSource(Formatter.java:213)

This is because it expects the default part to be separate. As a workaround, the default can be moved out of the switch expression and the formatter succeeds:

switch (reference.getReferenceTypeCase()) {
  case A -> ...
  case B -> throw new IllegalArgumentException("Unhandled");
  default -> throw new IllegalArgumentException("Unhandled");
}

Example code where this issue happenend:
https://github.com/nastra/substrait-java/blob/main/core/src/main/java/io/substrait/expression/proto/ProtoExpressionConverter.java#L114
https://github.com/nastra/substrait-java/blob/main/core/src/main/java/io/substrait/expression/proto/ProtoExpressionConverter.java#L65

class T {
  void f() {
    switch (reference.getReferenceTypeCase()) {
      case A -> foo();
      case B, default -> throw new IllegalArgumentException("Unhandled");
    }
  }
}
java  -jar google-java-format-1.15.0-all-deps.jar T.java
T.java:5:13: error: expected token: 'default'; generated - instead