Why a Consumer is not a Function.

java.util.function.Consumer does not extend java.util.function.Function. But what if you want a set of both types? Why isn’t there a ConsumerFunction?

A ConsumerFunction is not defined in java.util.function. You can easily do it yourself. But you will see that it’s not that simple. void is a keyword in Java. There is a class Void and (by reflection) you can even get an instance of Void. But you have to use a return statement to get a Function.

If you really need a ConsumerFunction for some reason you can use my implementation. It’s just one file so I put it on pastebin.com:

Here’s some example code:

// We need a variable of type ConsumerFunction:
ConsumerFunction<String> cf;
// We can assign a Lambda to it:
cf = (s) -> {
  return ConsumerFunction.VOID;
// Or convert a Consumer to a ConsumerFunction:
cf = ConsumerFunction.toFunction(System.out::println);
// And that's how we use it:
cf.accept("Hello World");
// A ConsumerFunction *is* a Function:
Function<String, Void> fn = cf;
// But it can be converted to a Consumer too:
Consumer<String> c = cf.toConsumer();

PS: If you are looking for a way to “convert” other functions such as IntFunction<T> => Function<Integer, T> then try this:

IntFunction<int[]> ctor = int[]::new;
Function<Integer, int[]> ctor2 = ctor::apply;

Leave a Reply

Your email address will not be published. Required fields are marked *