1

I'm surprised, why did the lambda expression can't be invoked at runtime correctly. is it a type inference error? The work aournd example is uncomment the explicit type argument declaration.

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();
        }
    }
}
Stefan Zobel
  • 3,182
  • 7
  • 28
  • 38
holi-java
  • 29,655
  • 7
  • 72
  • 83
  • @Holger sir, thank you mark the question as duplicated. good job. I find it for a while but I can't find the sufficient answer. – holi-java Feb 28 '18 at 14:18

1 Answers1

2

For this particular instance of this JDK bug, it should be noted that it does not fail if you declare the interface Marker after Collector

Fail:

interface Marker {}

interface Collector {
    IntStream stream();
}

Pass:

interface Collector {
    IntStream stream();
}
interface Marker {}
payloc91
  • 3,724
  • 1
  • 17
  • 45
  • thanks for your explaination! – holi-java Feb 28 '18 at 14:19
  • For this specific example, it’s unspecified whether the compiler should infer `Stream` or `Stream` for the stream type, so it’s not wrong if this decision depends on the order of the interface declarations, as it should not matter anyway, but of course, if one of the two possibilities triggers the bug, it does make a difference. – Holger Mar 01 '18 at 09:57