Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

It is possible to define the return type of a lambda expression?

Tags:

lambda

java-8

I have the following code

Random rnd = new Random();
rnd.ints().limit(100)
          .filter(i-> i > 0)
          .map(Math::sqrt)
          .forEach(System.out::println)

Which generates the following compile error:

Streams.java:12: error: incompatible types: bad return type in method reference
                .map(Math::sqrt)
                     ^
    double cannot be converted to int

If I use instead

.mapToDouble(Math::sqrt)

It works. The problem is that the compiler cannot infer the return type of the lambda expression used in map. Is there a way to specify it explicitly? I personally find the mapToxxx set of functions clumsy.

like image 829
pablochacin Avatar asked Feb 05 '23 16:02

pablochacin


1 Answers

This has nothing to do with "declaring the return type of your lambda." You're just specifying an invalid argument to map(), and the compiler is telling you so.

The map method in IntStream takes an IntUnaryOperator (a function from int to int). There is no method Math.sqrt that can be converted to this signature.

like image 197
Brian Goetz Avatar answered Feb 07 '23 18:02

Brian Goetz