有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java(下划线)是一个保留关键字

我刚刚将以下lambda表达式中的s替换为_

s -> Integer.parseInt(s)

Eclipse编译器说:

'_' should not be used as an identifier, since it is a reserved keyword from source level 1.8 on.

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


共 (3) 个答案

  1. # 2 楼答案

    这是JEP 302的第2阶段,它将添加下划线作为特殊字符来表示lambda表达式中未使用的参数

    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.

  2. # 3 楼答案

    要看的地方是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.

    因此,Eclipse消息具有误导性,特别是当为lambda参数生成错误或为任何其他_标识符生成警告时,这两种情况都使用相同的消息