scala地图的花括号和括号

时间:2018-05-03 01:27:58

标签: scala

 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

我会要求上述案例,为什么有些工作,而有些则不如评论所示

1 个答案:

答案 0 :(得分:0)

有关:

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

来自Scala Specification Anonymous Function definition

  

在单个无类型形式参数的情况下,(x)=> e可以缩写为x =>即如果匿名函数(x:T)=>用一个   单个类型参数显示为块的结果表达式,它   可以缩写为x:T =>即

对于类型Int Scala 可以在此上下文中推断出类型