Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

curly braces and parentheses for scala map

Tags:

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

I would ask for the above cases,why some work while others are not as the comments indicate

like image 432
Tom Avatar asked Nov 08 '22 07:11

Tom


1 Answers

For:

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

From Scala Specification Anonymous Function definition:

In the case of a single untyped formal parameter, (x) => e can be abbreviated to x => e. If an anonymous function (x: T) => e with a single typed parameter appears as the result expression of a block, it can be abbreviated to x: T => e.

and for type Int, Scala can infer this Type under this context.

like image 121
chengpohi Avatar answered Nov 15 '22 13:11

chengpohi