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
