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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With