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 test = Arrays.asList(
(int a, int b) -> a + b,
(double d) -> d * 2
);
Obviously Object does not work.
解决方案
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 test = Arrays.asList(
i0,
i1
);
That said, I'm not sure what's the point of storing these lambda expressions in a List. You can't use them without casting them back to the individual functional interface types.