Why can't we compose Function and Consumer just like we compose functions?
Function<Integer, String> a = Object::toString;
Consumer<String> b = x -> System.out.println(x);
Consumer<Integer> composed = a.andThen(b);
This seems like an obvious improvisation to the existing Function interface. Is there any reason why this capability was avoided in Java 8?
Also, is it a common practice to use an extended implementation of Function as follows?
interface FunctionImproved<T, R> extends Function<T, R> {
default Consumer<T> andThen(Consumer<R> consumer) {
return x -> consumer.accept(apply(x));
}
}
The
andThenmethod on aFunction<A0, A1>instance expects aFunction<A1, A2>, not aConsumer<A1>:It has a side-effect since our "consumer" (actually, it's a
Function<A1, A1>) will be returning an ignored value from the previousFunction<Integer, String> afunction. It's not what we want.There is a different way to compose a
Function<A0, A1>and aConsumer<A1>:which can be generalised to a utility method:
There are two options:
Having static methods that do some conversions between functional interfaces (like I did).
Extending these standard functional interfaces with default methods (like you did). Just choose a right meaningful name, not like
FunctionImproved.