JEP draft: Unnamed local variables and patterns

submited by
Style Pass
2022-10-06 00:30:26

Enhance the Java language with unnamed local variables, which can be initialized but not read from, and with unnamed patterns, which match everything and bind nothing. Both are denoted with the underscore (_) token.

There are some situations in Java where we have to declare a variable that we do not intend to use. While we have a way to sidestep a lengthy type name with var, yet we do not have a way to sidestep the names of unused local variables. These situations arise in constructs that require local variable declarations (such as catch blocks and try-with-resources), as well as in contexts that support patterns. Consider the following examples regarding local variable declarations:

Here, the catch formal ex must be declared, but is not used. This means that we must make up a name for it even though we don't plan to use it, and static analysis tools may complain to us about unused variables.

Similarly, we observe that code operating primarily via side-effects may assign the results of expressions to unused variables, specifically in blocks:

Leave a Comment