【发布时间】:2016-02-08 11:47:59
【问题描述】:
那么,为什么这段代码会编译?
public static void main(String[] args) {
Calculator test = (Calculator & Sumator) (a, b) -> a + b;
System.out.println(test.calculate(2, 3));
Sumator sumator = (Calculator & Sumator) (a, b) -> a + b; // does compile, but throws an Exception
sumator.test();
Both both = (Both) (a, b) -> a + b; // does not compile
}
interface Calculator {
public int calculate(int a, int b);
}
interface Sumator {
public int test();
public int test3(int a, int b);
}
// intersection of both types
interface Both extends Sumator, Calculator {
}
这有点误导,我确实知道转换为交叉类型,我已经阅读了 jls,但仍然令人困惑。
这有点道理
Serializable & Comparable
会编译,因为这两者之间的结果(合成类型)是一个功能接口,但为什么会这样:
Calculator & Sumator
有效吗?该合成类型不是函数式接口。
【问题讨论】:
-
你使用哪个
JDK?它并非在所有情况下都能编译。 -
@Andremoniy 1.8.0_45
-
它给了
multiple non-overriding abstract methods found in interface INT#1 where INT#1 is an intersection type: INT#1 extends Object,Calculator,Sumator -
@Andremoniy 你是对的。似乎是 Eclipse 编译器问题..
标签: java eclipse lambda java-8