Can pass reference variable pointing to Lambda in Java Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Can pass reference variable pointing to Lambda in Java without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I as trying out some Spring reactive code and following is relevant piece of code

Supplier<Stream<Long>> longStreamSupplier = ()
            -> LongStream.iterate(0,
                    nextLong -> nextLong + 1).boxed();

Flux<Long> fooIds = Flux.fromStream(longStreamSupplier); 

Last line above gives compilation error in Intellj IDE saying there is not method which accepts the type.

However if i convert it to following :

Flux<Long> fooIds = Flux.fromStream(() -> LongStream
                    .iterate(0, nextLong -> nextLong + 1)
                    .boxed());

This works fine. Why it cant accept a reference variable pointing to the same lambda expression i am passing in second piece of code?

Answer

That’s because the longStreamSupplier variable has type Y<X<A>>, while the method expects an argument with type Y<X<? extends A>>, and these types aren’t interchangeable.

edit

you can change the variable type to make the first example compile,

Supplier<Stream<? extends Long>> longStreamSupplier = ..
We are here to answer your question about Can pass reference variable pointing to Lambda in Java - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji