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