Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to chain to a Java 8 Supplier

Supplier does not provide a andThen method, so chaining another Function to the result of a Supplier is not possible. Is the only alternative to use a Function<Void, R> that does not get any parameter?

In other words, if Supplier.andThen() existed I could write:

 Supplier<Exception> cleanedExceptionSupplier = exceptionSupplier.andThen( 
     e -> clean(e));

Since it does not exist, how can I cleanly implement cleanedExceptionSupplier?

like image 247
Daniel Nitzan Avatar asked Jan 05 '23 02:01

Daniel Nitzan


2 Answers

Instead of:

 Supplier<T> supp2 = supp1.andThen(function);

(which, uses a method you've seen doesn't exist)

... you could use:

 Supplier<T> supp2 = () -> function.apply(supp1.get());
like image 199
slim Avatar answered Jan 07 '23 14:01

slim


Just adding my alternate solution as a candidate here

Function<Void, R> supplierAsFunction = v -> returnSomethingOfR();

supplierAsFunction.andThen(function).apply(null); 

Applying null as a parameter is rather ugly but this solution maintains functional style while using only java.util.function classes.

like image 36
Daniel Nitzan Avatar answered Jan 07 '23 15:01

Daniel Nitzan