【问题标题】:Lambda and cast intersection type (Eclipse compiler bug)Lambda 和 cast 交集类型(Eclipse 编译器错误)
【发布时间】: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


【解决方案1】:

这是一个 bug in Eclipse,已针对 Eclipse Neon (4.6) 的里程碑 6 进行了修复。

【讨论】:

    【解决方案2】:

    嗯,这似乎是一个 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
    

    【讨论】:

    • 您应该在您的问题中明确提及这是 Eclipse 编译问题。此外,您应该始终检查原始 JDK 编译器的编译问题
    • @Andremoniy 是的,我觉得不这样做很愚蠢,你的评论让我“啊哈时刻”。谢谢
    • 请将 Eclipse 版本(或 JDT 插件版本)添加到问题或答案中。这可能会帮助更多的读者。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多