Given the code fragment:



BiFunction<Integer, Double, Integer> val = (t1, t2) -> t1 + t2; // line n1
System.out.println(val.apply(10, 10.5));

What is the result?
A.

20

B.

20.5

C. A compilation error occurs at line n1.
D. A compilation error occurs at line n2.

題解

BiFunction為可以接受兩個參數的Functional Interface,擷取JDK的程式碼如下:

public interface BiFunction<T, U, R> {
    R apply(T t, U u);
}

這題的line n1會發生編譯錯誤,因為BiFunction的回傳泛型型態為Integer,但是第二個參數U的泛型型態為Double。若直接把Integer物件加上Double物件或是int加上double,出來的結果都會是double,double無法隱含式(implicit)轉型為Integer。

若使用顯式(explicit)轉型的話,可以解決這個問題,如下:

BiFunction<Integer, Double, Integer> val = (t1, t2) -> (int) (t1 + t2); // line n1
System.out.println(val.apply(10, 10.5));

如此一來,輸出結果就會是:

20