当类实现相同的接口时,Lambda表达式因LambdaConversionException而失败?

时间:2018-02-28 13:45:18

标签: java java-8

我很惊讶,为什么无法在运行时正确调用lambda表达式。这是一个类型推断错误? 工作aournd示例取消注释显式类型参数声明。

public class LambdaConversionTest {
    @Test
    public void whyDidLambdaExpressionFailsWithLambdaConversionException() {
        try {
            //      v--- when uncomment it, the behavior is what I expected
            Stream./*<Collector>*/of(new Robot(), new Puller())
                  .flatMapToInt(Collector::stream).sum();
            fail("fails with expected behavior");
        } catch (BootstrapMethodError why) {
            assertThat(why.getCause().getMessage()
                 ,containsString("Invalid receiver type interface "));
        }
    }

    interface Marker {
    }

    interface Collector {
        IntStream stream();
    }

    class Robot implements Collector, Marker {
        @Override
        public IntStream stream() {
            return IntStream.empty();
        }
    }

    class Puller implements Collector, Marker {
        @Override
        public IntStream stream() {
            return IntStream.empty();
        }
    }
}

1 个答案:

答案 0 :(得分:2)

对于this JDK bug的这个特定实例,应该注意的是,如果在processing one processing three

之后声明接口Marker,它不会失败

故障:

Collector

通过:

interface Marker {}

interface Collector {
    IntStream stream();
}