首页 > 解决方案 > scala map 的花括号和括号

问题描述

 Array(7,8,9) map (x:Int=>x+1) //1).error, identifier expected but integer literal found.
 Array(7,8,9) map {x:Int=>x+1} //2) correct  
 Array(7,8,9) map ((x:Int)=>x+1) //3) correct
 Array(7,8,9) map (x=>x+1) //4 correct
 Array(7,8,9) map {x=>x+1} //5 correct
 Array(7,8,9) map x=>x+1   //6 error

我会询问上述情况,为什么有些工作,而另一些则没有如评论所示

标签: scala

解决方案


为了:

 Array(7,8,9) map {x:Int=>x+1} //2) correct  
 Array(7,8,9) map {x=>x+1} //5 correct

来自Scala 规范匿名函数定义

在单个无类型形式参数的情况下,(x) => e 可以缩写为 x => e。如果带有单个类型参数的匿名函数 (x: T) => e 作为块的结果表达式出现,则可以缩写为 x: T => e。

对于 type IntScala可以在这个上下文下推断这个Type 。


推荐阅读