_ (下划线)是保留关键字

我刚刚用 _代替了下面的 lambda 表达式中的 s:

s -> Integer.parseInt(s)

Eclipse 编译器表示:

“ _”不应该用作标识符,因为它是从源级别1.8开始的保留关键字。

我没有找到任何解释在 JLS 3.9词汇结构/关键字。

29467 次浏览

The place to look is JLS §15.27.1. Lambda Parameters

It is a compile-time error if a lambda parameter has the name _ (that is, a single underscore character).

The use of the variable name _ in any context is discouraged. Future versions of the Java programming language may reserve this name as a keyword and/or give it special semantics.

So the Eclipse message is misleading, especially as the same message is used for both cases, when an error is generated for a lambda parameter or when a warning is generated for any other _ identifier.

Java Language Changes for Java SE 9 https://docs.oracle.com/javase/9/language/toc.htm#JSLAN-GUID-16A5183A-DC0D-4A96-B9D8-AAC9671222DD

From Java 9, the _ character cannot be used as an identifier anymore, not just within the lambda context

The underscore character is not a legal name.

If you use the underscore character ("_") an identifier, your source code can no longer be compiled.

It is the Phase 2 of JEP 302, that is going to add underscore as a special character to denote unused parameters in lambda expressions.

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.