我有以下代码
Random rnd = new Random();
rnd.ints().limit(100)
.filter(i-> i > 0)
.map(Math::sqrt)
.forEach(System.out::println)
Run Code Online (Sandbox Code Playgroud)
这会生成以下编译错误:
Streams.java:12: error: incompatible types: bad return type in method reference
.map(Math::sqrt)
^
double cannot be converted to int
Run Code Online (Sandbox Code Playgroud)
如果我改用
.mapToDouble(Math::sqrt)
Run Code Online (Sandbox Code Playgroud)
有用.问题是编译器无法推断map中使用的lambda表达式的返回类型.有没有办法明确指定它?我个人觉得mapToxxx功能集笨拙.
这与"声明lambda的返回类型"无关.你只是指定一个无效的参数map(),编译器告诉你.
的map在方法IntStream需要一个IntUnaryOperator(从函数int到int).没有Math.sqrt可以转换为此签名的方法.
| 归档时间: |
|
| 查看次数: |
1826 次 |
| 最近记录: |