OCP Question 17, Explanation

Given the code fragment:

UnaryOperator<Integer> unop = x -> x*2;             // line 1
List<Double> nums = Arrays.asList(10.0, 20.0);
nums.stream()
    .filter(x -> x > 15.0)
    .map(x -> unop.apply(x))                        // line 2
    .forEach(x -> System.out.print(x));

What is the result?

A. 40.0
B. 40
C. A compilation error occurs at line 1.
D. A compilation error occurs at line 2.

 

The correct answer is D.

UnaryOperator is typed to Integer but map()’s lambda wants to pass a Double to the UnaryOperator’s functional method. Re-parameterizing unop to <Double> would fix the comperr.

Leave Comment

Your email address will not be published.