Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create composite lambda expression in java 8

I'm trying to use lambda expressions in Java 8. The type of the expression that I want to write is:

BiConsumer<String, BiConsumer<Boolean,Integer>> cc2;

I should be able to write an expression looking a bit like this:

cc2 = (s,(b,i)) -> { System.out.println(s+b+i); }; // this does not compile

Unfortunately I can't find the exact syntax I must use.

like image 338
niedomnie Avatar asked Dec 18 '22 15:12

niedomnie


1 Answers

The type BiConsumer<String, BiConsumer<Boolean,Integer>> declares a BiConsumer, that is to say a consumer that consumes 2, and only 2, arguments. Of those two arguments, one is declared to be of type String, while the other is declared of type BiConsumer<Boolean,Integer>.

As such, this would compile:

BiConsumer<String, BiConsumer<Boolean,Integer>> cc2 = (s, c) -> {};

s would be of type String and c would be of type BiConsumer. The arguments to c would need to be captured and won't be lambda parameters.

That is not what you want though: you actually want to consume 3 arguments, not 2. There is no built-in functional interface for this requirement, but you can make your own:

@FunctionalInterface
interface TriConsumer<A,B,C> {
    void accept(A a, B b, C c);
}

Then, you can use it with

TriConsumer<String,Boolean,Integer> tri = (s, b, i) -> System.out.println(s+b+i);

Alternatively, you can make use of currying by declaring a Function that takes a String and would return the bi-consumer:

Function<String, BiConsumer<Boolean,Integer>> f = s -> (b, i) -> System.out.println(s+b+i);
f.apply("foo").accept(true, 1);
like image 128
Tunaki Avatar answered Dec 21 '22 23:12

Tunaki