JLS 3.9 -- Role of underscore

Alex Buckley alex.buckley at oracle.com
Fri Oct 18 17:54:10 UTC 2019


The following issue was raised on the java-se-spec-comments list:

https://mail.openjdk.java.net/pipermail/java-se-spec-comments/2019-October/000003.html

"In the Java Language Specification JSE13 Edition, 3.9 Keywords, the 
paragraph that explains const and goto are "reserved but not currently 
used" should also mention the underscore (_) keyword. As far as I can 
tell, it is "not currently used" either, with the intent being to 
eventually have it indicate an unused lambda, method, or catch formal 
parameter in a declaration (JEP 302: Lambda Leftovers)."

3.9 should indeed call out the underscore keyword as reserved, and 
summarize the policy from JEP 302, which I record here for convenience:

-----
Treatment of underscores

In many languages, it is common to use an underscore (_) to denote an 
unnamed lambda parameter (and similarly for method and exception 
parameters):

BiFunction<Integer, String, String> biss = (i, _) -> String.valueOf(i);

This allows stronger static checking of unused arguments, and also 
allows multiple arguments to be marked as unused. However, because 
underscore was a valid identifier as of Java 8, compatibility required 
us to take a more indirect path to getting to where underscore could 
serve this role in Java. Phase 1 was forbidding underscore as a lambda 
formal parameter name in Java 8 (this had no compatibility consequence, 
since lambdas did not exist previously) and a warning was issued for 
using underscore as an identifier in other places. Phase 2 came in Java 
9, when this warning became an error. We are now free to complete the 
planned rehabilitation of underscore to indicate an unused lambda, 
method, or catch formal parameter.
-----

Alex


More information about the jls-jvms-spec-comments mailing list