Lambda and cast intersection type (Eclipse compile

2019-05-10 02:38发布

So, why does this code compile?

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 {

}

This is sort of misleading, I do know about casting to an intersection type, I've read the jls, but still confusing.

It sort of makes sense why

 Serializable & Comparable 

would compile, since the result (the synthetic type) between those two is a functional interface, but why does :

 Calculator & Sumator 

works? That synthetic type is not a functional interface.

2条回答
三岁会撩人
2楼-- · 2019-05-10 03:04

This was a bug in Eclipse which has been fixed for milestone 6 towards Eclipse Neon (4.6).

查看更多
forever°为你锁心
3楼-- · 2019-05-10 03:19

Well, it seems like an Eclipse compiler bug probably, because it does not compile under javac. I wonder how to fix this or if there is already an issue opened for this.

   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
查看更多
登录 后发表回答