Eugene February 2016

Lambda and cast intersection type (Eclipse compiler bug)

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.

Answers


Eugene February 2016

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


Stephan Herrmann February 2016

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

Post Status

Asked in February 2016
Viewed 3,110 times
Voted 12
Answered 2 times

Search




Leave an answer