我有以下代码
Random rnd = new Random();
rnd.ints().limit(100)
.filter(i-> i > 0)
.map(Math::sqrt)
.forEach(System.out::println)
这会产生以下编译错误:
Streams.java:12: error: incompatible types: bad return type in method reference
.map(Math::sqrt)
^
double cannot be converted to int
如果我改用
.mapToDouble(Math::sqrt)
有用。问题是编译器无法推断 map 中使用的 lambda 表达式的返回类型。有没有办法明确指定它?我个人找了
mapToxxx
函数集笨拙。
最佳答案
这与“声明 lambda 的返回类型”无关。您只是为 map()
指定了一个无效参数,编译器告诉你。map
IntStream
中的方法需要一个 IntUnaryOperator
(从 int
到 int
的函数)。没有方法Math.sqrt
可以转换为这个签名。
关于lambda - 可以定义 lambda 表达式的返回类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43333414/