What is the formal difference in Scala between braces and parentheses, and when should they be used?

后端 未结 9 1248
萌比男神i
萌比男神i 2020-11-22 07:09

What is the formal difference between passing arguments to functions in parentheses () and in braces {}?

The feeling I got from the Pro

9条回答
  •  無奈伤痛
    2020-11-22 07:51

    There are a couple of different rules and inferences going on here: first of all, Scala infers the braces when a parameter is a function, e.g. in list.map(_ * 2) the braces are inferred, it's just a shorter form of list.map({_ * 2}). Secondly, Scala allows you to skip the parentheses on the last parameter list, if that parameter list has one parameter and it is a function, so list.foldLeft(0)(_ + _) can be written as list.foldLeft(0) { _ + _ } (or list.foldLeft(0)({_ + _}) if you want to be extra explicit).

    However, if you add case you get, as others have mentioned, a partial function instead of a function, and Scala will not infer the braces for partial functions, so list.map(case x => x * 2) won't work, but both list.map({case x => 2 * 2}) and list.map { case x => x * 2 } will.

提交回复
热议问题