Functional programming idiom for applying a series of void functions to a single value

749 Views Asked by At

Given a value foo and a Stream of Consumer<Foo> void functions, what's the most concise way to apply each function to the value? Right now I have

consumers.forEach(c -> c.accept(foo));

which isn't terrible, but I suspect there might be some way to turn this inside out and do it with just method references (no explicit lambda). Possibly something with a singleton list and zip()?

I'd be happy with a straight Java 8 answer, or Vavr, or Scala.

(Note that this is not a fold, or at least not the usual foldLeft/foldRight application; if there were return values, I'd be discarding them, not iterating on them.)

3

There are 3 best solutions below

0
On

You could reduce your consumers by means of the Consumer.andThen method and then apply the resulting consumer to the foo argument:

consumers.reduce(Consumer::andThen).ifPresent(c -> c.accept(foo));

But there's no difference between this approach and yours, and yours' is shorter.

5
On

In Scala you should be able to do

consumers.foreach(_.accept(foo));
1
On

I think the real concern here is that methods which return void are a code smell. Why couldn't they return something useful, or at least carry out their side-effect and then return the original value, which allows for better chaining. I think that would be a preferable approach, but short of that, I think the forEach approach is ok.