Compiletime error while using java.util.Function#identity in Stream#flatMap(Function<T,Stream<R>>)

Viewed 62

Merry Christmas,

I was tinkering with some java.util.Streams when some irregular behavior caught my eye. I was simply trying to flatten a list containing several streams of integer values likes this example:

List<Stream> list = new ArrayList<>();
list.add(Stream.of( 1,2 ));
list.add(Stream.of( 3,4 ));

list.stream().flatMap( s -> s ).forEach( System.out::println );

This minimal code snippet works without any issue. And usually when I see a lambda expression like s -> s I think I'd be able to simply replace it with java.util.Function#identity() since it's pretty much the same however in doing so I came upon this compile-time issue:

D:\Development\Java\Playground\src\Main.java:15:30
java: incompatible types: cannot infer type-variable(s) R,T
    (argument mismatch; java.util.function.Function<java.util.stream.Stream,java.util.stream.Stream> cannot be converted to java.util.function.Function<? super java.util.stream.Stream,? extends java.util.stream.Stream<? extends java.lang.Object>>)

I myself cant quite explain the difference between using java.util.Function#identity() and s -> s. So why does this compile time issue occur? My guess is that it has something to do with type erasure but I am not certain and can't explain this for myself.

I am using OpenJDK v16.0.1.

1 Answers

Perhaps this is what you were going for. The type should be Stream<Integer>

List<Stream<Integer>> list = new ArrayList<>();
list.add(Stream.of( 1,2 ));
list.add(Stream.of( 3,4 ));

list.stream().flatMap( s -> s ).forEach( System.out::println );

prints

1
2
3
4
        
Related