Eugene
Eugene

Reputation: 120848

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.

Upvotes: 3

Views: 309

Answers (2)

Stephan Herrmann
Stephan Herrmann

Reputation: 8178

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

Upvotes: 1

Eugene
Eugene

Reputation: 120848

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

Upvotes: 0

Related Questions