1
votes

I am using the below code to create java.util.function Function> instance and use the return value of Function instance to pass it to the ExecutorService.submit() method.

However I get a "Symbol Not Found" exception. Please help

Below is the code snippet:

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

The compiler throws the error: java: cannot find symbol symbol: method doubleIt_1(java.lang.Integer) location: class declarative.L12LegacyToFunctionalInterface_4

Please help...

1
The IntelliJ editor however shows a different exception: "Method Call Expected" - Soumya Panigrahi
Cause doubleIt_1 is not a function it is a variable (functor). It is not JavaScript where you can interchange function and variable. - Lemonov
Well, that means that your class doesn't have any method named doubleIt_1 and taking an Integer as argument. - JB Nizet
In addition to my previous you call pool.submit(int) cause doubleIt_1(index) return integer - Lemonov

1 Answers

0
votes

You must call the method of Function, to call the doubleIt_1 implementation, like this:

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

The Function interface just have 4 methods, the core one is apply(T):R, where we pass the T value, and it returns the R response. Example:

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