使用java.util.function函数接口给出“找不到符号”错误

时间:2017-05-25 11:05:43

标签: java lambda

我使用以下代码创建java.util.function函数>实例并使用Function实例的返回值将其传递给ExecutorService.submit()方法。

但是我得到了“未找到符号”的例外情况。请帮忙

以下是代码段:

   //Approach-1
    Function<Integer, Callable<Integer>> doubleIt_1 = (index) -> {return () -> {return index * 2;};};
    //Approach-2
    Function<Integer, Callable<Integer>> doubleIt_2 = (index) -> () -> {return  index * 2;};
    //Approach 3
    Function<Integer, Callable<Integer>> doubleIt_3 = (index) -> () -> index * 2;

    //Use the "doubleIt" lambda function defined above to pass as a Lambda function to ExecutorService threadpool's submit method.
    Function<Integer, Future<Integer>> task = (Integer index) ->  pool.submit(doubleIt_1(index));

编译器抛出错误: java:找不到符号   symbol:方法doubleIt_1(java.lang.Integer)   location:class declarative.L12LegacyToFunctionalInterface_4

请帮忙......

1 个答案:

答案 0 :(得分:0)

您必须调用Function的方法,以调用doubleIt_1实现,如下所示:

//Use the "doubleIt" lambda function defined above to pass as a Lambda function to ExecutorService threadpool's submit method.
Function<Integer, Future<Integer>> task = (Integer index) ->  pool.submit(doubleIt_1.apply(index));

Function接口只有4个方法,核心一个是apply(T):R,我们传递T值,然后返回R响应。例如:

public static void main(String[] args) {
    Function<Integer, Double> t = new Function<Integer, Double>() {

        @Override
        public Double apply(Integer t) {
            return t.doubleValue();
        }
    };

    callFunction(t, 10);

    t = (i) -> i.doubleValue();
    callFunction(t, 10);

    t = (Integer i) -> {return i.doubleValue();};
    callFunction(t, 10);

    callFunction((i) -> i.doubleValue(), 10);

}

private static Double callFunction(Function<Integer, Double> f, Integer i){
    return f.apply(i);
}