那么,为什么这段代码会编译?
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
的作品?合成类型不是功能接口。
答案 0 :(得分:1)
这是一个bug in Eclipse已经针对里程碑6修复了Eclipse Neon(4.6)。
答案 1 :(得分:0)
好吧,它似乎是一个Eclipse编译器错误,因为它不能在javac下编译。我想知道如何解决这个问题,或者是否已经为此打开了一个问题。
MultipleCastsBound.java:5: error: incompatible types: INT#1 is not a functional interface
Calculator test = (Calculator & Sumator) (a, b) -> a + b;
^
multiple non-overriding abstract methods found in interface INT#1
where INT#1 is an intersection type:
INT#1 extends Object,Calculator,Sumator
MultipleCastsBound.java:8: error: incompatible types: INT#1 is not a functional interface
Sumator sumator = (Calculator & Sumator) (a, b) -> a + b;
^
multiple non-overriding abstract methods found in interface INT#1
where INT#1 is an intersection type:
INT#1 extends Object,Calculator,Sumator
2 errors