I'd like to create an array of lambda. The problem is that the lambda could be different from each other. Example:
private interface I0 {
int interface0(int a, int b);
}
private interface I1 {
int interface1(double d);
}
Now, how can I declare a list which can contain both I0 and I1?
List<Object> test = Arrays.asList(
(int a, int b) -> a + b,
(double d) -> d * 2
);
Obviously Object
does not work.
You could cast to the respective Interface like:
List<Object> test = Arrays.asList(
(I0) (int a, int b) -> a + b,
(I1) (double d) -> (int) (d * 2)
);
despite this being shorter, I would also consider Eran's answer maybe it is more readable and easier to understand (if having more functions). And I also can't see the use case for such a construct...
It gets even shorter (not necessarily better):
List<Object> test = Arrays.asList(
(I0) (a, b) -> a + b,
(I1) d -> (int) (d * 2)
);
You must assign the lambda expressions to variables of the functional interface types first.
Otherwise the compiler cannot infer the types of these lambda expressions.
I0 i0 = (int a, int b) -> a + b;
I1 i1 = (double d) -> (int) (d * 2);
List<Object> test = Arrays.asList(
i0,
i1
);
That said, I'm not sure what's the point of storing these lambda expressions in a List<Object>
. You can't use them without casting them back to the individual functional interface types.
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