JDK-8335136 : Underscore as parameter name in one-parameter functional types fails to compile
  • Type: Bug
  • Component: tools
  • Sub-Component: javac
  • Affected Version: 23
  • Priority: P4
  • Status: New
  • Resolution: Unresolved
  • OS: generic
  • CPU: generic
  • Submitted: 2024-06-25
  • Updated: 2024-06-26
Related Reports
Relates :  
Description
A DESCRIPTION OF THE PROBLEM :
Compilation fails if yield statement is followed by underscore, even if it is legal syntax, like yield _ -> {}. This is issue that has been present in jdk since introduction of unnamed variables and patterns

STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
Compile following code:

public class SwitchYieldAndUnderscore {
  public static void main(String[] args) {
    Consumer<String> value = switch (args[0]) {
      case "foo" -> {
        yield _ -> {};
      }
      default -> throw new AssertionError();
    };
  }
}

EXPECTED VERSUS ACTUAL BEHAVIOR :
EXPECTED -
Compilation successful
ACTUAL -
Compilation failes with 2 errors:
";" exprected
"=" exprected

---------- BEGIN SOURCE ----------
public class SwitchYieldAndUnderscore {
  public static void main(String[] args) {
    Consumer<String> value = switch (args[0]) {
      case "foo" -> {
        yield _ -> {};
      }
      default -> throw new AssertionError();
    };
  }
}
---------- END SOURCE ----------

CUSTOMER SUBMITTED WORKAROUND :
Enclose _ in paretheses like so: yield (_) -> {}

FREQUENCY : always



Comments
From JDK-8061549, _ is not allowed as a legal identifier names. Closed as not an issue.
26-06-2024