Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is a single underscore character an illegal name for a lambda parameter?

I tried naming a lambda parameter _, e.g. (a cut down version):

Consumer<Object> c = _ -> {}; 

as I wanted to signify that a parameter was being ignored, but I got the following compiler error:

use of '_' as an identifier is forbidden for lambda parameters

This was a surprise for me. Interestingly, two underscores is OK:

Consumer<Object> c = __ -> {}; // no compile error 

So it's not the underscore character in general, but a single one.

Why is the single-underscore name specifically forbidden?

like image 244
Bohemian Avatar asked Dec 30 '15 01:12

Bohemian


People also ask

Is _ a keyword?

_ (underscore) is a reserved keyword.

Why underscore is a keyword in Java?

Java For TestersIn 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 is underscore reserved in Java?

Underscore(_) is a symbol that is used to combine multi-words in a single identifier sometimes refers to a variable in a programming context. In Java, to create a lengthy variable, we prefer to use underscore (_) such as employee_id , employee_name etc.


1 Answers

The reason is expressed in this post from Brian Goetz himself:

We are "reclaiming" the syntactic real estate of "_" from the space of identifiers for use in future language features. However, because there are existing programs that might use it, it is a warning for identifiers that occur in existing syntactic positions for 8, and an error for lambda formals (since there is no existing code with lambdas.)

like image 88
Bohemian Avatar answered Sep 22 '22 11:09

Bohemian