How to specify function types for void (not Void) methods in Java8?
Pocket-sized solution: Use Consumer<T>
for methods with a single parameter and void return type:
For void methods without parameters, Runnable
is your friend:
And for methods with two parameters and void return, utilize BiConsumer<T, U>
:
Making sense of Functional Interfaces
Single-parameter void methods: Consumer<T>
For functions that do their job silently (a.k.a. return void) and take one parameter, Consumer<T>
works wonders. The function fits snugly inside the accept(T t)
method:
Two-parameter void methods and beyond: BiConsumer and friends
When a function takes two witnesses but remains silent (void), BiConsumer<T, U>
handles the business. If there are more than two confidants, custom functional interfaces or object encapsulation come to the rescue.
Parameter-less void scenarios: Runnable
Run Runnable
run! The workhorse interface of Java, known for its use in threading, is also a perfect match for parameter-less void-return functions:
When generic doesn't cut it: Custom Functional Interfaces
Custom-made solution for you: custom functional interfaces. It's like naming your high-functioning pet rock:
Critically, they can make your intent clear and code flexible.
Making void cool again with Method References
Nobody in Java land writes Lambdas longer than they absolutely need to. Enter method references. When the referenced method is void, it's Consumer
time again:
Void’s compatibility patch: Null
Those pesky APIs expecting Function<T, Void>
can be accommodated with null
:
Naming interfaces: The art of clarity
A well-named functional interface is like a well-marked road. Choose names to illuminate the direction of your code:
Was this article helpful?