Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

_ (underscore) is a reserved keyword

I've just replaced s in the following lambda expression by _:

s -> Integer.parseInt(s) 

Eclipse compiler says:

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

I haven't found any explanation in the JLS §3.9 Lexical Structure / Keywords.

like image 228
Aubin Avatar asked May 07 '14 17:05

Aubin


People also ask

Is underscore a reserved keyword in Java?

In earlier versions of Java, the underscore ("_") has used as an identifier or to create a variable name. Since Java 9, the underscore character is a reserved keyword and can't be used as an identifier or variable name.

Why underscore is used in Java?

In Java SE 7 and later, any number of underscore characters ( _ ) can appear anywhere between digits in a numerical literal. This feature enables you, for example, to separate groups of digits in numeric literals, which can improve the readability of your code.


1 Answers

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.

like image 84
Holger Avatar answered Sep 20 '22 20:09

Holger