在Java中声明lambda数组 [英] Declare array of lambdas in Java

查看:146
本文介绍了在Java中声明lambda数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个lambda数组.问题在于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);
}

现在,我如何声明一个既可以包含I0也可以包含I1的列表?

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
);

显然Object不起作用.

推荐答案

必须首先将lambda表达式分配给功能接口类型的变量.

You must assign the lambda expressions to variables of the functional interface types first.

否则,编译器无法推断这些lambda表达式的类型.

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
);

也就是说,我不确定将这些lambda表达式存储在List<Object>中有什么意义.您必须先将其转换回各个功能接口类型,然后才能使用它们.

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.

这篇关于在Java中声明lambda数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆