Unnamed variables and patterns can be used when a declaration is required but the value is never used. They are denoted by the underscore character: _.
It was finalized in JDK 22 by JEP 456.
See JEP 456 for the full feature details.
It can be used in many ways.
However one useful place for it is concurrency code with CompletableFuture.
Mainly in scenarios with many asynchronous calls, e.g.:
1 | |
When we need all async calls to complete before working with the data, .allOf comes in handy:
1 | |
Then, with .thenApply, we can retrieve the values and perform the operation we need:
1 | |
Finally, we use .thenAccept to print the computation result:
1 | |
This prints the value: 110.
At this point, we can take advantage of unnamed variables:
1 | |
The variable unused has no meaning here because its value is never used.
Since .allOf returns a CompletableFuture<Void>.
The .thenApply parameter is always null.
Being just a required variable that is never used, we can replace it with _:
1 | |
This is where unnamed variables are beautiful: they remove a meaningless name and make the code cleaner.
xoff.