What is the formal difference between passing arguments to functions in parentheses ()
and in braces {}
?
The feeling I got from the Pro
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.