Can I determine the return type of a lambda expression in 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 compilation 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 the map. Is there any way to state this explicitly? I personally find the KTTXXX feature set awkward.

+4
source share
1 answer

This has nothing to do with "declaring your lambda return type." You simply specify an invalid argument on map(), and the compiler tells you that.

map IntStream IntUnaryOperator ( int int). Math.sqrt, .

+8

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


All Articles