I found that parentheses are not required when partial function used as parameter in Scala
val array = Array(2)
array.map(x => x + 1)
array.map { case x => x + 1 }
{ case x => x + 1 } defines a partial function here, so it should be array.map({ case x => x + 1 }) , but there are no parentheses.So what happend here? Is that syntactic sugar?
The real advantage of this is DSLs when you are passing argument by name. It is also helpful for both partial and complete functions that span more than one line. Without this, you would have to put parenthesis outside the curly braces for all such cases.
System.out.println("bar") is an expression with type Unit. Your function twice only expects a single parameter, so your call with round braces won’t compile, as you have several expressions, where only one is required.
The curly braces group several expressions together into one expression, so this way you can use multiple lines. The result of the grouped expression is the last expression inside. In this case, println returns Unit, which has only a single instance, the empty tuple (). So your whole block also returns Unit, like a single println.