Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare array of lambdas in Java

Tags:

java

lambda

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.

like image 858
Surcle Avatar asked Dec 05 '17 09:12

Surcle


2 Answers

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)
);
like image 192
user85421 Avatar answered Sep 18 '22 18:09

user85421


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.

like image 42
Eran Avatar answered Sep 20 '22 18:09

Eran