Search code examples
javagenericslambdajava-8java-stream

Problems understanding the Stream.generate static method signature


Why didn't Java choose this signature <T> Stream<T> Stream.generate(Supplier<? extends T> supplier) over this one <T> Stream<T> Stream.generate(Supplier<T> supplier) ?

I mean the below example (doesn't compile) is correct as a supplier of Strings is also valid in a stream of CharSequences, no ?

Supplier<String> constantHello = () -> "Hello";

long count = Stream.<CharSequence>generate(constantHello).count();

Solution

  • It's a bug. See https://bugs.openjdk.java.net/browse/JDK-8132097

    It has been corrected in java 9. As you can see here, the method declaration is now

    static <T> Stream<T> generate​(Supplier<? extends T> s)