Gangmax Blog

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

From here and here.

Today I read some code like this:

1
2
config.addChangeListener(
__ -> updateConfig());

At the first glance the “__“ part looks like some special syntax, actually it’s just the parameter name of the lambda which is not used in the implementation. You can use any name for it. The interesting part is: why not use “_“?

The answer is that, “_“ is illegal for lambda parameter in Java 8, and illegal for any identifier in Java 9. Here is some quote from the JDK 8 document:

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.

And here is another post about the understore changes in Java 9.

So I think a better choice is to use “$” to replace “_“ like this:

1
2
config.addChangeListener(
$ -> updateConfig());

Comments