Compilation time: no instance (s) of type (s) of type U

The following statement, although meaningless, seems syntactically sound.

final Stream<LongStream> foobar = IntStream.empty()
    .flatMap(x -> IntStream.empty()
        .mapToObj(y -> IntStream.empty()
            .mapToLong(z -> 1))); //compilation error here on `z -> 1`

However, it does not compile, returning:

java: incompatible types: invalid return type in lambda expression there is no instance (s) of type (s) of type U, so java.util.stream.Stream corresponds to java.util.stream.IntStream

However, if you delay the tablet, everything works fine:

final Stream<LongStream> foobar = IntStream.empty()
    .mapToObj(x -> IntStream.empty()
        .mapToObj(y -> IntStream.empty()
            .mapToLong(z -> 1)))
    .flatMap(x -> x);

What is the difference between .mapToObj(..).flatMap(..)and simple .flatMap(..)? Is there a way to eliminate the extra tablet?

+4
source share
2 answers

.mapToObj(..).flatMap(..)and .flatMap(..)expect completely different signatures.

.mapToObj(..).flatMap(..) int -> Object Object -> Stream<?>.

.flatMap(..) int -> IntStream.

, int -> Stream<LongStream>, int -> IntStream.

:

IntStream.empty().flatMap(x -> Stream.of(LongStream.empty()));
+5

, , :

IntFunction<LongStream> f1 = y -> IntStream.empty().mapToLong(z -> 1);
IntFunction<LongStream> f2 = x -> IntStream.empty().mapToObj(f1);
final Stream<LongStream> foobar = IntStream.empty().flatMap(f2);

:

2 LongStream, a Stream<LongStream>, int LongStream. , LongStream, flatMapToLong.

flatMap 3 int -> int, . mapToObj, , .

, :

IntFunction<LongStream> f1 = y -> IntStream.empty().mapToLong(z -> 1);
IntFunction<LongStream> f2 = x -> IntStream.empty().mapToObj(f1).flatMapToLong(i -> i);
final Stream<LongStream> foobar = IntStream.empty().mapToObj(f2);
+1

Source: https://habr.com/ru/post/1672319/


All Articles