OCP Question 3, Explanation

Given the code fragment:

BiFunction<Integer, Double, Integer> value = (p1, p2) -> p1 + p2; // n1
System.out.println(value.apply(1, 1.5));                          // n2

What is the result?
A. 2
B. 2.5
C. A compilation error occurs at line n1
D. A compilation error occurs at line n2

The correct answer is option C.

Everything looks fine about this snippet – except for its BiFunction’s return value: we’re trying to add an Integer to a Double (yeah, yeah, through autoboxing and unboxing, all this boring stuff; oh! just remembered: do watch this video where Joshua Bloch says adding autoboxing and unboxing to Java 5 was “total disasters”:

(jump to ~17:47)

Back to the current Problem. The result of addition will be, naturally, of type Double but our BiFunction expects an Integer. Rewriting the reftype as BiFunction<Integer, Double, Double> would fix the comperr and make the option B correct.

Leave Comment

Your email address will not be published. Required fields are marked *