Omitting curly braces in scala for multiple lines - scala

I've seen some samples of scala code where multiple lines of code are used as a block of code with no curly braces, for instance:
x match {
case a:Int =>
val b = 1
val c = b +3
println("hello!")
c
case _ => 5
}
same with some very long functions that use an implicit param of the form:
a.map { implicit x =>
// many, many complex lines of code
}
as opposed to:
a.map { implicit x => {
// many, many complex lines of code
}}
I've seen a lot of documentation/FAQ stating that multiple lines of code should be surrounded always by curly braces, but could not find an explanation for these exceptions. I would love to understand or have a good intuition so that does not feel like magic to me.

In a case statement, the body, while it looks like a block is actually the expression part of a function literal, following the form of arg => expr. Since case statements are terminated by either another case statement or the closing curly bracket of the case block, the function literal's bounds are implicitly defined and the expression does not need its own block delimiters

Related

() vs {} in foreach case [duplicate]

What is the formal difference between passing arguments to functions in parentheses () and in braces {}?
The feeling I got from the Programming in Scala book is that Scala's pretty flexible and I should use the one I like best, but I find that some cases compile while others don't.
For instance (just meant as an example; I would appreciate any response that discusses the general case, not this particular example only):
val tupleList = List[(String, String)]()
val filtered = tupleList.takeWhile( case (s1, s2) => s1 == s2 )
=> error: illegal start of simple expression
val filtered = tupleList.takeWhile{ case (s1, s2) => s1 == s2 }
=> fine.
I tried once to write about this, but I gave up in the end, as the rules are somewhat diffuse. Basically, you’ll have to get the hang of it.
Perhaps it is best to concentrate on where curly braces and parentheses can be used interchangeably: when passing parameters to method calls. You may replace curly braces with parentheses if, and only if, the method expects a single parameter. For example:
List(1, 2, 3).reduceLeft{_ + _} // valid, single Function2[Int,Int] parameter
List{1, 2, 3}.reduceLeft(_ + _) // invalid, A* vararg parameter
However, there’s more you need to know to better grasp these rules.
Increased compile checking with parens
The authors of Spray recommend round parens because they give increased compile checking. This is especially important for DSLs like Spray. By using parens you are telling the compiler that it should only be given a single line; therefore if you accidentally give it two or more, it will complain. Now this isn’t the case with curly braces – if for example you forget an operator somewhere, then your code will compile, and you get unexpected results and potentially a very hard bug to find. Below is contrived (since the expressions are pure and will at least give a warning), but makes the point:
method {
1 +
2
3
}
method(
1 +
2
3
)
The first compiles, the second gives error: ')' expected but integer literal found. The author wanted to write 1 + 2 + 3.
One could argue it’s similar for multi-parameter methods with default arguments; it’s impossible to accidentally forget a comma to separate parameters when using parens.
Verbosity
An important often overlooked note about verbosity. Using curly braces inevitably leads to verbose code since the Scala style guide clearly states that closing curly braces must be on their own line:
… the closing brace is on its own line immediately following the last
line of the function.
Many auto-reformatters, like in IntelliJ, will automatically perform this reformatting for you. So try to stick to using round parens when you can.
Infix Notation
When using infix notation, like List(1,2,3) indexOf (2) you can omit parentheses if there is only one parameter and write it as List(1, 2, 3) indexOf 2. This is not the case of dot-notation.
Note also that when you have a single parameter that is a multi-token expression, like x + 2 or a => a % 2 == 0, you have to use parentheses to indicate the boundaries of the expression.
Tuples
Because you can omit parentheses sometimes, sometimes a tuple needs extra parentheses like in ((1, 2)), and sometimes the outer parentheses can be omitted, like in (1, 2). This may cause confusion.
Function/Partial Function literals with case
Scala has a syntax for function and partial function literals. It looks like this:
{
case pattern if guard => statements
case pattern => statements
}
The only other places where you can use case statements are with the match and catch keywords:
object match {
case pattern if guard => statements
case pattern => statements
}
try {
block
} catch {
case pattern if guard => statements
case pattern => statements
} finally {
block
}
You cannot use case statements in any other context. So, if you want to use case, you need curly braces. In case you are wondering what makes the distinction between a function and partial function literal, the answer is: context. If Scala expects a function, a function you get. If it expects a partial function, you get a partial function. If both are expected, it gives an error about ambiguity.
Expressions and Blocks
Parentheses can be used to make subexpressions. Curly braces can be used to make blocks of code (this is not a function literal, so beware of trying to use it like one). A block of code consists of multiple statements, each of which can be an import statement, a declaration or an expression. It goes like this:
{
import stuff._
statement ; // ; optional at the end of the line
statement ; statement // not optional here
var x = 0 // declaration
while (x < 10) { x += 1 } // stuff
(x % 5) + 1 // expression
}
( expression )
So, if you need declarations, multiple statements, an import or anything like that, you need curly braces. And because an expression is a statement, parentheses may appear inside curly braces. But the interesting thing is that blocks of code are also expressions, so you can use them anywhere inside an expression:
( { var x = 0; while (x < 10) { x += 1}; x } % 5) + 1
So, since expressions are statements, and blocks of codes are expressions, everything below is valid:
1 // literal
(1) // expression
{1} // block of code
({1}) // expression with a block of code
{(1)} // block of code with an expression
({(1)}) // you get the drift...
Where they are not interchangeable
Basically, you can’t replace {} with () or vice versa anywhere else. For example:
while (x < 10) { x += 1 }
This is not a method call, so you can’t write it in any other way. Well, you can put curly braces inside the parentheses for the condition, as well as use parentheses inside the curly braces for the block of code:
while ({x < 10}) { (x += 1) }
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.
There is an effort from the community to standardize the usage of braces and parentheses, see Scala Style Guide (page 21): http://www.codecommit.com/scala-style-guide.pdf
The recommended syntax for higher order methods calls is to always use braces, and to skip the dot:
val filtered = tupleList takeWhile { case (s1, s2) => s1 == s2 }
For "normal" metod calls you should use the dot and parentheses.
val result = myInstance.foo(5, "Hello")
I don't think there is anything particular or complex about curly braces in Scala. To master the seeming-complex usage of them in Scala, just keep a couple of simple things in mind:
curly braces form a block of code, which evaluates to the last line of code (almost all languages do this)
a function if desired can be generated with the block of code (follows rule 1)
curly braces can be omitted for one-line code except for a case clause (Scala choice)
parentheses can be omitted in function call with code block as a parameter (Scala choice)
Let's explain a couple of examples per the above three rules:
val tupleList = List[(String, String)]()
// doesn't compile, violates case clause requirement
val filtered = tupleList.takeWhile( case (s1, s2) => s1 == s2 )
// block of code as a partial function and parentheses omission,
// i.e. tupleList.takeWhile({ case (s1, s2) => s1 == s2 })
val filtered = tupleList.takeWhile{ case (s1, s2) => s1 == s2 }
// curly braces omission, i.e. List(1, 2, 3).reduceLeft({_+_})
List(1, 2, 3).reduceLeft(_+_)
// parentheses omission, i.e. List(1, 2, 3).reduceLeft({_+_})
List(1, 2, 3).reduceLeft{_+_}
// not both though it compiles, because meaning totally changes due to precedence
List(1, 2, 3).reduceLeft _+_ // res1: String => String = <function1>
// curly braces omission, i.e. List(1, 2, 3).foldLeft(0)({_ + _})
List(1, 2, 3).foldLeft(0)(_ + _)
// parentheses omission, i.e. List(1, 2, 3).foldLeft(0)({_ + _})
List(1, 2, 3).foldLeft(0){_ + _}
// block of code and parentheses omission
List(1, 2, 3).foldLeft {0} {_ + _}
// not both though it compiles, because meaning totally changes due to precedence
List(1, 2, 3).foldLeft(0) _ + _
// error: ';' expected but integer literal found.
List(1, 2, 3).foldLeft 0 (_ + _)
def foo(f: Int => Unit) = { println("Entering foo"); f(4) }
// block of code that just evaluates to a value of a function, and parentheses omission
// i.e. foo({ println("Hey"); x => println(x) })
foo { println("Hey"); x => println(x) }
// parentheses omission, i.e. f({x})
def f(x: Int): Int = f {x}
// error: missing arguments for method f
def f(x: Int): Int = f x
I think it is worth explaining their usage in function calls and why various things happen. As someone already said curly braces define a block of code, which is also an expression so can be put where expression is expected and it will be evaluated. When evaluated, its statements are executed and last's statement value is the result of whole block evaluation (somewhat like in Ruby).
Having that we can do things like:
2 + { 3 } // res: Int = 5
val x = { 4 } // res: x: Int = 4
List({1},{2},{3}) // res: List[Int] = List(1,2,3)
Last example is just a function call with three parameters, of which each is evaluated first.
Now to see how it works with function calls let's define simple function that take another function as a parameter.
def foo(f: Int => Unit) = { println("Entering foo"); f(4) }
To call it, we need to pass function that takes one param of type Int, so we can use function literal and pass it to foo:
foo( x => println(x) )
Now as said before we can use block of code in place of an expression so let's use it
foo({ x => println(x) })
What happens here is that code inside {} is evaluated, and the function value is returned as a value of the block evaluation, this value is then passed to foo. This is semantically the same as previous call.
But we can add something more:
foo({ println("Hey"); x => println(x) })
Now our code block contains two statements, and because it is evaluated before foo is executed, what happens is that first "Hey" is printed, then our function is passed to foo, "Entering foo" is printed and lastly "4" is printed.
This looks a bit ugly though and Scala lets us to skip the parenthesis in this case, so we can write:
foo { println("Hey"); x => println(x) }
or
foo { x => println(x) }
That looks much nicer and is equivalent to the former ones. Here still block of code is evaluated first and the result of evaluation (which is x => println(x)) is passed as an argument to foo.
Because you are using case, you are defining a partial function and partial functions require curly braces.
Increased compile checking with parens
The authors of Spray, recommend that round parens give increased compile checking. This is especially important for DSLs like Spray. By using parens you are telling the compiler that it should only be given a single line, therefore if you accidentally gave it two or more, it will complain. Now this isn't the case with curly braces, if for example, you forget an operator somewhere your code will compile, you get unexpected results and potentially a very hard bug to find. Below is contrived (since the expressions are pure and will at least give a warning), but makes the point
method {
1 +
2
3
}
method(
1 +
2
3
)
The first compiles, the second gives error: ')' expected but integer literal found. the author wanted to write 1 + 2 + 3.
One could argue it's similar for multi-parameter methods with default arguments; it's impossible to accidentally forget a comma to separate parameters when using parens.
Verbosity
An important often overlooked note about verbosity. Using curly braces inevitably leads to verbose code since the scala style guide clearly states that closing curly braces must be on their own line: http://docs.scala-lang.org/style/declarations.html "... the closing brace is on its own line immediately following the last line of the function." Many auto-reformatters, like in Intellij, will automatically perform this reformatting for you. So try to stick to using round parens when you can. E.g. List(1, 2, 3).reduceLeft{_ + _} becomes:
List(1, 2, 3).reduceLeft {
_ + _
}
Parenthesis in an ideal coding style is basically used for single line code.
But if the particular piece of code is multiline then using braces is a better way.
With braces, you got semicolon induced for you and parentheses not. Consider takeWhile function, since it expects partial function, only {case xxx => ??? } is valid definition instead of parentheses around case expression.

Spark: Difference using map() and map{} [duplicate]

What is the formal difference between passing arguments to functions in parentheses () and in braces {}?
The feeling I got from the Programming in Scala book is that Scala's pretty flexible and I should use the one I like best, but I find that some cases compile while others don't.
For instance (just meant as an example; I would appreciate any response that discusses the general case, not this particular example only):
val tupleList = List[(String, String)]()
val filtered = tupleList.takeWhile( case (s1, s2) => s1 == s2 )
=> error: illegal start of simple expression
val filtered = tupleList.takeWhile{ case (s1, s2) => s1 == s2 }
=> fine.
I tried once to write about this, but I gave up in the end, as the rules are somewhat diffuse. Basically, you’ll have to get the hang of it.
Perhaps it is best to concentrate on where curly braces and parentheses can be used interchangeably: when passing parameters to method calls. You may replace curly braces with parentheses if, and only if, the method expects a single parameter. For example:
List(1, 2, 3).reduceLeft{_ + _} // valid, single Function2[Int,Int] parameter
List{1, 2, 3}.reduceLeft(_ + _) // invalid, A* vararg parameter
However, there’s more you need to know to better grasp these rules.
Increased compile checking with parens
The authors of Spray recommend round parens because they give increased compile checking. This is especially important for DSLs like Spray. By using parens you are telling the compiler that it should only be given a single line; therefore if you accidentally give it two or more, it will complain. Now this isn’t the case with curly braces – if for example you forget an operator somewhere, then your code will compile, and you get unexpected results and potentially a very hard bug to find. Below is contrived (since the expressions are pure and will at least give a warning), but makes the point:
method {
1 +
2
3
}
method(
1 +
2
3
)
The first compiles, the second gives error: ')' expected but integer literal found. The author wanted to write 1 + 2 + 3.
One could argue it’s similar for multi-parameter methods with default arguments; it’s impossible to accidentally forget a comma to separate parameters when using parens.
Verbosity
An important often overlooked note about verbosity. Using curly braces inevitably leads to verbose code since the Scala style guide clearly states that closing curly braces must be on their own line:
… the closing brace is on its own line immediately following the last
line of the function.
Many auto-reformatters, like in IntelliJ, will automatically perform this reformatting for you. So try to stick to using round parens when you can.
Infix Notation
When using infix notation, like List(1,2,3) indexOf (2) you can omit parentheses if there is only one parameter and write it as List(1, 2, 3) indexOf 2. This is not the case of dot-notation.
Note also that when you have a single parameter that is a multi-token expression, like x + 2 or a => a % 2 == 0, you have to use parentheses to indicate the boundaries of the expression.
Tuples
Because you can omit parentheses sometimes, sometimes a tuple needs extra parentheses like in ((1, 2)), and sometimes the outer parentheses can be omitted, like in (1, 2). This may cause confusion.
Function/Partial Function literals with case
Scala has a syntax for function and partial function literals. It looks like this:
{
case pattern if guard => statements
case pattern => statements
}
The only other places where you can use case statements are with the match and catch keywords:
object match {
case pattern if guard => statements
case pattern => statements
}
try {
block
} catch {
case pattern if guard => statements
case pattern => statements
} finally {
block
}
You cannot use case statements in any other context. So, if you want to use case, you need curly braces. In case you are wondering what makes the distinction between a function and partial function literal, the answer is: context. If Scala expects a function, a function you get. If it expects a partial function, you get a partial function. If both are expected, it gives an error about ambiguity.
Expressions and Blocks
Parentheses can be used to make subexpressions. Curly braces can be used to make blocks of code (this is not a function literal, so beware of trying to use it like one). A block of code consists of multiple statements, each of which can be an import statement, a declaration or an expression. It goes like this:
{
import stuff._
statement ; // ; optional at the end of the line
statement ; statement // not optional here
var x = 0 // declaration
while (x < 10) { x += 1 } // stuff
(x % 5) + 1 // expression
}
( expression )
So, if you need declarations, multiple statements, an import or anything like that, you need curly braces. And because an expression is a statement, parentheses may appear inside curly braces. But the interesting thing is that blocks of code are also expressions, so you can use them anywhere inside an expression:
( { var x = 0; while (x < 10) { x += 1}; x } % 5) + 1
So, since expressions are statements, and blocks of codes are expressions, everything below is valid:
1 // literal
(1) // expression
{1} // block of code
({1}) // expression with a block of code
{(1)} // block of code with an expression
({(1)}) // you get the drift...
Where they are not interchangeable
Basically, you can’t replace {} with () or vice versa anywhere else. For example:
while (x < 10) { x += 1 }
This is not a method call, so you can’t write it in any other way. Well, you can put curly braces inside the parentheses for the condition, as well as use parentheses inside the curly braces for the block of code:
while ({x < 10}) { (x += 1) }
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.
There is an effort from the community to standardize the usage of braces and parentheses, see Scala Style Guide (page 21): http://www.codecommit.com/scala-style-guide.pdf
The recommended syntax for higher order methods calls is to always use braces, and to skip the dot:
val filtered = tupleList takeWhile { case (s1, s2) => s1 == s2 }
For "normal" metod calls you should use the dot and parentheses.
val result = myInstance.foo(5, "Hello")
I don't think there is anything particular or complex about curly braces in Scala. To master the seeming-complex usage of them in Scala, just keep a couple of simple things in mind:
curly braces form a block of code, which evaluates to the last line of code (almost all languages do this)
a function if desired can be generated with the block of code (follows rule 1)
curly braces can be omitted for one-line code except for a case clause (Scala choice)
parentheses can be omitted in function call with code block as a parameter (Scala choice)
Let's explain a couple of examples per the above three rules:
val tupleList = List[(String, String)]()
// doesn't compile, violates case clause requirement
val filtered = tupleList.takeWhile( case (s1, s2) => s1 == s2 )
// block of code as a partial function and parentheses omission,
// i.e. tupleList.takeWhile({ case (s1, s2) => s1 == s2 })
val filtered = tupleList.takeWhile{ case (s1, s2) => s1 == s2 }
// curly braces omission, i.e. List(1, 2, 3).reduceLeft({_+_})
List(1, 2, 3).reduceLeft(_+_)
// parentheses omission, i.e. List(1, 2, 3).reduceLeft({_+_})
List(1, 2, 3).reduceLeft{_+_}
// not both though it compiles, because meaning totally changes due to precedence
List(1, 2, 3).reduceLeft _+_ // res1: String => String = <function1>
// curly braces omission, i.e. List(1, 2, 3).foldLeft(0)({_ + _})
List(1, 2, 3).foldLeft(0)(_ + _)
// parentheses omission, i.e. List(1, 2, 3).foldLeft(0)({_ + _})
List(1, 2, 3).foldLeft(0){_ + _}
// block of code and parentheses omission
List(1, 2, 3).foldLeft {0} {_ + _}
// not both though it compiles, because meaning totally changes due to precedence
List(1, 2, 3).foldLeft(0) _ + _
// error: ';' expected but integer literal found.
List(1, 2, 3).foldLeft 0 (_ + _)
def foo(f: Int => Unit) = { println("Entering foo"); f(4) }
// block of code that just evaluates to a value of a function, and parentheses omission
// i.e. foo({ println("Hey"); x => println(x) })
foo { println("Hey"); x => println(x) }
// parentheses omission, i.e. f({x})
def f(x: Int): Int = f {x}
// error: missing arguments for method f
def f(x: Int): Int = f x
I think it is worth explaining their usage in function calls and why various things happen. As someone already said curly braces define a block of code, which is also an expression so can be put where expression is expected and it will be evaluated. When evaluated, its statements are executed and last's statement value is the result of whole block evaluation (somewhat like in Ruby).
Having that we can do things like:
2 + { 3 } // res: Int = 5
val x = { 4 } // res: x: Int = 4
List({1},{2},{3}) // res: List[Int] = List(1,2,3)
Last example is just a function call with three parameters, of which each is evaluated first.
Now to see how it works with function calls let's define simple function that take another function as a parameter.
def foo(f: Int => Unit) = { println("Entering foo"); f(4) }
To call it, we need to pass function that takes one param of type Int, so we can use function literal and pass it to foo:
foo( x => println(x) )
Now as said before we can use block of code in place of an expression so let's use it
foo({ x => println(x) })
What happens here is that code inside {} is evaluated, and the function value is returned as a value of the block evaluation, this value is then passed to foo. This is semantically the same as previous call.
But we can add something more:
foo({ println("Hey"); x => println(x) })
Now our code block contains two statements, and because it is evaluated before foo is executed, what happens is that first "Hey" is printed, then our function is passed to foo, "Entering foo" is printed and lastly "4" is printed.
This looks a bit ugly though and Scala lets us to skip the parenthesis in this case, so we can write:
foo { println("Hey"); x => println(x) }
or
foo { x => println(x) }
That looks much nicer and is equivalent to the former ones. Here still block of code is evaluated first and the result of evaluation (which is x => println(x)) is passed as an argument to foo.
Because you are using case, you are defining a partial function and partial functions require curly braces.
Increased compile checking with parens
The authors of Spray, recommend that round parens give increased compile checking. This is especially important for DSLs like Spray. By using parens you are telling the compiler that it should only be given a single line, therefore if you accidentally gave it two or more, it will complain. Now this isn't the case with curly braces, if for example, you forget an operator somewhere your code will compile, you get unexpected results and potentially a very hard bug to find. Below is contrived (since the expressions are pure and will at least give a warning), but makes the point
method {
1 +
2
3
}
method(
1 +
2
3
)
The first compiles, the second gives error: ')' expected but integer literal found. the author wanted to write 1 + 2 + 3.
One could argue it's similar for multi-parameter methods with default arguments; it's impossible to accidentally forget a comma to separate parameters when using parens.
Verbosity
An important often overlooked note about verbosity. Using curly braces inevitably leads to verbose code since the scala style guide clearly states that closing curly braces must be on their own line: http://docs.scala-lang.org/style/declarations.html "... the closing brace is on its own line immediately following the last line of the function." Many auto-reformatters, like in Intellij, will automatically perform this reformatting for you. So try to stick to using round parens when you can. E.g. List(1, 2, 3).reduceLeft{_ + _} becomes:
List(1, 2, 3).reduceLeft {
_ + _
}
Parenthesis in an ideal coding style is basically used for single line code.
But if the particular piece of code is multiline then using braces is a better way.
With braces, you got semicolon induced for you and parentheses not. Consider takeWhile function, since it expects partial function, only {case xxx => ??? } is valid definition instead of parentheses around case expression.

why does scala pattern match require curly bracket [duplicate]

What is the formal difference between passing arguments to functions in parentheses () and in braces {}?
The feeling I got from the Programming in Scala book is that Scala's pretty flexible and I should use the one I like best, but I find that some cases compile while others don't.
For instance (just meant as an example; I would appreciate any response that discusses the general case, not this particular example only):
val tupleList = List[(String, String)]()
val filtered = tupleList.takeWhile( case (s1, s2) => s1 == s2 )
=> error: illegal start of simple expression
val filtered = tupleList.takeWhile{ case (s1, s2) => s1 == s2 }
=> fine.
I tried once to write about this, but I gave up in the end, as the rules are somewhat diffuse. Basically, you’ll have to get the hang of it.
Perhaps it is best to concentrate on where curly braces and parentheses can be used interchangeably: when passing parameters to method calls. You may replace curly braces with parentheses if, and only if, the method expects a single parameter. For example:
List(1, 2, 3).reduceLeft{_ + _} // valid, single Function2[Int,Int] parameter
List{1, 2, 3}.reduceLeft(_ + _) // invalid, A* vararg parameter
However, there’s more you need to know to better grasp these rules.
Increased compile checking with parens
The authors of Spray recommend round parens because they give increased compile checking. This is especially important for DSLs like Spray. By using parens you are telling the compiler that it should only be given a single line; therefore if you accidentally give it two or more, it will complain. Now this isn’t the case with curly braces – if for example you forget an operator somewhere, then your code will compile, and you get unexpected results and potentially a very hard bug to find. Below is contrived (since the expressions are pure and will at least give a warning), but makes the point:
method {
1 +
2
3
}
method(
1 +
2
3
)
The first compiles, the second gives error: ')' expected but integer literal found. The author wanted to write 1 + 2 + 3.
One could argue it’s similar for multi-parameter methods with default arguments; it’s impossible to accidentally forget a comma to separate parameters when using parens.
Verbosity
An important often overlooked note about verbosity. Using curly braces inevitably leads to verbose code since the Scala style guide clearly states that closing curly braces must be on their own line:
… the closing brace is on its own line immediately following the last
line of the function.
Many auto-reformatters, like in IntelliJ, will automatically perform this reformatting for you. So try to stick to using round parens when you can.
Infix Notation
When using infix notation, like List(1,2,3) indexOf (2) you can omit parentheses if there is only one parameter and write it as List(1, 2, 3) indexOf 2. This is not the case of dot-notation.
Note also that when you have a single parameter that is a multi-token expression, like x + 2 or a => a % 2 == 0, you have to use parentheses to indicate the boundaries of the expression.
Tuples
Because you can omit parentheses sometimes, sometimes a tuple needs extra parentheses like in ((1, 2)), and sometimes the outer parentheses can be omitted, like in (1, 2). This may cause confusion.
Function/Partial Function literals with case
Scala has a syntax for function and partial function literals. It looks like this:
{
case pattern if guard => statements
case pattern => statements
}
The only other places where you can use case statements are with the match and catch keywords:
object match {
case pattern if guard => statements
case pattern => statements
}
try {
block
} catch {
case pattern if guard => statements
case pattern => statements
} finally {
block
}
You cannot use case statements in any other context. So, if you want to use case, you need curly braces. In case you are wondering what makes the distinction between a function and partial function literal, the answer is: context. If Scala expects a function, a function you get. If it expects a partial function, you get a partial function. If both are expected, it gives an error about ambiguity.
Expressions and Blocks
Parentheses can be used to make subexpressions. Curly braces can be used to make blocks of code (this is not a function literal, so beware of trying to use it like one). A block of code consists of multiple statements, each of which can be an import statement, a declaration or an expression. It goes like this:
{
import stuff._
statement ; // ; optional at the end of the line
statement ; statement // not optional here
var x = 0 // declaration
while (x < 10) { x += 1 } // stuff
(x % 5) + 1 // expression
}
( expression )
So, if you need declarations, multiple statements, an import or anything like that, you need curly braces. And because an expression is a statement, parentheses may appear inside curly braces. But the interesting thing is that blocks of code are also expressions, so you can use them anywhere inside an expression:
( { var x = 0; while (x < 10) { x += 1}; x } % 5) + 1
So, since expressions are statements, and blocks of codes are expressions, everything below is valid:
1 // literal
(1) // expression
{1} // block of code
({1}) // expression with a block of code
{(1)} // block of code with an expression
({(1)}) // you get the drift...
Where they are not interchangeable
Basically, you can’t replace {} with () or vice versa anywhere else. For example:
while (x < 10) { x += 1 }
This is not a method call, so you can’t write it in any other way. Well, you can put curly braces inside the parentheses for the condition, as well as use parentheses inside the curly braces for the block of code:
while ({x < 10}) { (x += 1) }
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.
There is an effort from the community to standardize the usage of braces and parentheses, see Scala Style Guide (page 21): http://www.codecommit.com/scala-style-guide.pdf
The recommended syntax for higher order methods calls is to always use braces, and to skip the dot:
val filtered = tupleList takeWhile { case (s1, s2) => s1 == s2 }
For "normal" metod calls you should use the dot and parentheses.
val result = myInstance.foo(5, "Hello")
I don't think there is anything particular or complex about curly braces in Scala. To master the seeming-complex usage of them in Scala, just keep a couple of simple things in mind:
curly braces form a block of code, which evaluates to the last line of code (almost all languages do this)
a function if desired can be generated with the block of code (follows rule 1)
curly braces can be omitted for one-line code except for a case clause (Scala choice)
parentheses can be omitted in function call with code block as a parameter (Scala choice)
Let's explain a couple of examples per the above three rules:
val tupleList = List[(String, String)]()
// doesn't compile, violates case clause requirement
val filtered = tupleList.takeWhile( case (s1, s2) => s1 == s2 )
// block of code as a partial function and parentheses omission,
// i.e. tupleList.takeWhile({ case (s1, s2) => s1 == s2 })
val filtered = tupleList.takeWhile{ case (s1, s2) => s1 == s2 }
// curly braces omission, i.e. List(1, 2, 3).reduceLeft({_+_})
List(1, 2, 3).reduceLeft(_+_)
// parentheses omission, i.e. List(1, 2, 3).reduceLeft({_+_})
List(1, 2, 3).reduceLeft{_+_}
// not both though it compiles, because meaning totally changes due to precedence
List(1, 2, 3).reduceLeft _+_ // res1: String => String = <function1>
// curly braces omission, i.e. List(1, 2, 3).foldLeft(0)({_ + _})
List(1, 2, 3).foldLeft(0)(_ + _)
// parentheses omission, i.e. List(1, 2, 3).foldLeft(0)({_ + _})
List(1, 2, 3).foldLeft(0){_ + _}
// block of code and parentheses omission
List(1, 2, 3).foldLeft {0} {_ + _}
// not both though it compiles, because meaning totally changes due to precedence
List(1, 2, 3).foldLeft(0) _ + _
// error: ';' expected but integer literal found.
List(1, 2, 3).foldLeft 0 (_ + _)
def foo(f: Int => Unit) = { println("Entering foo"); f(4) }
// block of code that just evaluates to a value of a function, and parentheses omission
// i.e. foo({ println("Hey"); x => println(x) })
foo { println("Hey"); x => println(x) }
// parentheses omission, i.e. f({x})
def f(x: Int): Int = f {x}
// error: missing arguments for method f
def f(x: Int): Int = f x
I think it is worth explaining their usage in function calls and why various things happen. As someone already said curly braces define a block of code, which is also an expression so can be put where expression is expected and it will be evaluated. When evaluated, its statements are executed and last's statement value is the result of whole block evaluation (somewhat like in Ruby).
Having that we can do things like:
2 + { 3 } // res: Int = 5
val x = { 4 } // res: x: Int = 4
List({1},{2},{3}) // res: List[Int] = List(1,2,3)
Last example is just a function call with three parameters, of which each is evaluated first.
Now to see how it works with function calls let's define simple function that take another function as a parameter.
def foo(f: Int => Unit) = { println("Entering foo"); f(4) }
To call it, we need to pass function that takes one param of type Int, so we can use function literal and pass it to foo:
foo( x => println(x) )
Now as said before we can use block of code in place of an expression so let's use it
foo({ x => println(x) })
What happens here is that code inside {} is evaluated, and the function value is returned as a value of the block evaluation, this value is then passed to foo. This is semantically the same as previous call.
But we can add something more:
foo({ println("Hey"); x => println(x) })
Now our code block contains two statements, and because it is evaluated before foo is executed, what happens is that first "Hey" is printed, then our function is passed to foo, "Entering foo" is printed and lastly "4" is printed.
This looks a bit ugly though and Scala lets us to skip the parenthesis in this case, so we can write:
foo { println("Hey"); x => println(x) }
or
foo { x => println(x) }
That looks much nicer and is equivalent to the former ones. Here still block of code is evaluated first and the result of evaluation (which is x => println(x)) is passed as an argument to foo.
Because you are using case, you are defining a partial function and partial functions require curly braces.
Increased compile checking with parens
The authors of Spray, recommend that round parens give increased compile checking. This is especially important for DSLs like Spray. By using parens you are telling the compiler that it should only be given a single line, therefore if you accidentally gave it two or more, it will complain. Now this isn't the case with curly braces, if for example, you forget an operator somewhere your code will compile, you get unexpected results and potentially a very hard bug to find. Below is contrived (since the expressions are pure and will at least give a warning), but makes the point
method {
1 +
2
3
}
method(
1 +
2
3
)
The first compiles, the second gives error: ')' expected but integer literal found. the author wanted to write 1 + 2 + 3.
One could argue it's similar for multi-parameter methods with default arguments; it's impossible to accidentally forget a comma to separate parameters when using parens.
Verbosity
An important often overlooked note about verbosity. Using curly braces inevitably leads to verbose code since the scala style guide clearly states that closing curly braces must be on their own line: http://docs.scala-lang.org/style/declarations.html "... the closing brace is on its own line immediately following the last line of the function." Many auto-reformatters, like in Intellij, will automatically perform this reformatting for you. So try to stick to using round parens when you can. E.g. List(1, 2, 3).reduceLeft{_ + _} becomes:
List(1, 2, 3).reduceLeft {
_ + _
}
Parenthesis in an ideal coding style is basically used for single line code.
But if the particular piece of code is multiline then using braces is a better way.
With braces, you got semicolon induced for you and parentheses not. Consider takeWhile function, since it expects partial function, only {case xxx => ??? } is valid definition instead of parentheses around case expression.

What's the reasoning behind adding the "case" keyword to Scala?

Apart from:
case class A
... case which is quite useful?
Why do we need to use case in match? Wouldn't:
x match {
y if y > 0 => y * 2
_ => -1
}
... be much prettier and concise?
Or why do we need to use case when a function takes a tuple? Say, we have:
val z = List((1, -1), (2, -2), (3, -3)).zipWithIndex
Now, isn't:
z map { case ((a, b), i) => a + b + i }
... way uglier than just:
z map (((a, b), i) => a + b + i)
...?
First, as we know, it is possible to put several statements for the same case scenario without needing some separation notation, just a line jump, like :
x match {
case y if y > 0 => y * 2
println("test")
println("test2") // these 3 statements belong to the same "case"
}
If case was not needed, compiler would have to find a way to know when a line is concerned by the next case scenario.
For example:
x match {
y if y > 0 => y * 2
_ => -1
}
How compiler would know whether _ => -1 belongs to the first case scenario or represents the next case?
Moreover, how compiler would know that the => sign doesn't represent a literal function but the actual code for the current case?
Compiler would certainly need a kind of code like this allowing cases isolation:
(using curly braces, or anything else)
x match {
{y if y > 0 => y * 2}
{_ => -1} // confusing with literal function notation
}
And surely, solution (provided currently by scala) using case keyword is a lot more readable and understandable than putting some way of separation like curly braces in my example.
Adding to #Mik378's answer:
When you write this: (a, b) => something, you are defining an anonymous Function2 - a function that takes two parameters.
When you write this: case (a, b) => something, you are defining an anonymous PartialFunction that takes one parameter and matches it against a pair.
So you need the case keyword to differentiate between these two.
The second issue, anonymous functions that avoid the case, is a matter of debate:
https://groups.google.com/d/msg/scala-debate/Q0CTZNOekWk/z1eg3dTkCXoJ
Also: http://www.scala-lang.org/old/node/1260
For the first issue, the choice is whether you allow a block or an expression on the RHS of the arrow.
In practice, I find that shorter case bodies are usually preferable, so I can certainly imagine your alternative syntax resulting in crisper code.
Consider one-line methods. You write:
def f(x: Int) = 2 * x
then you need to add a statement. I don't know if the IDE is able to auto-add parens.
def f(x: Int) = { val res = 2*x ; res }
That seems no worse than requiring the same syntax for case bodies.
To review, a case clause is case Pattern Guard => body.
Currently, body is a block, or a sequence of statements and a result expression.
If body were an expression, you'd need braces for multiple statements, like a function.
I don't think => results in ambiguities since function literals don't qualify as patterns, unlike literals like 1 or "foo".
One snag might be: { case foo => ??? } is a "pattern matching anonymous function" (SLS 8.5). Obviously, if the case is optional or eliminated, then { foo => ??? } is ambiguous. You'd have to distinguish case clauses for anon funs (where case is required) and case clauses in a match.
One counter-argument for the current syntax is that, in an intuition deriving from C, you always secretly hope that your match will compile to a switch table. In that metaphor, the cases are labels to jump to, and a label is just the address of a sequence of statements.
The alternative syntax might encourage a more inlined approach:
x match {
C => c(x)
D => d(x)
_ => ???
}
#inline def c(x: X) = ???
//etc
In this form, it looks more like a dispatch table, and the match body recalls the Map syntax, Map(a -> 1, b -> 2), that is, a tidy simplification of the association.
One of the key aspects of code readability is the words that grab your attention. For example,
return grabs your attention when you see it because you know that it is such a decisive action (breaking out of the function and possible sending a value back to the caller).
Another example is break--not that I like break, but it gets your attention.
I would agree with #Mik378 that case in Scala is more readable than the alternatives. Besides the compiler confusion he mentions, it gets your attention.
I am all for concise code, but there is a line between concise and illegible. I will gladly make the trade of 4n characters (where n is the number of cases) for the substantial readability that I get in return.

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

What is the formal difference between passing arguments to functions in parentheses () and in braces {}?
The feeling I got from the Programming in Scala book is that Scala's pretty flexible and I should use the one I like best, but I find that some cases compile while others don't.
For instance (just meant as an example; I would appreciate any response that discusses the general case, not this particular example only):
val tupleList = List[(String, String)]()
val filtered = tupleList.takeWhile( case (s1, s2) => s1 == s2 )
=> error: illegal start of simple expression
val filtered = tupleList.takeWhile{ case (s1, s2) => s1 == s2 }
=> fine.
I tried once to write about this, but I gave up in the end, as the rules are somewhat diffuse. Basically, you’ll have to get the hang of it.
Perhaps it is best to concentrate on where curly braces and parentheses can be used interchangeably: when passing parameters to method calls. You may replace curly braces with parentheses if, and only if, the method expects a single parameter. For example:
List(1, 2, 3).reduceLeft{_ + _} // valid, single Function2[Int,Int] parameter
List{1, 2, 3}.reduceLeft(_ + _) // invalid, A* vararg parameter
However, there’s more you need to know to better grasp these rules.
Increased compile checking with parens
The authors of Spray recommend round parens because they give increased compile checking. This is especially important for DSLs like Spray. By using parens you are telling the compiler that it should only be given a single line; therefore if you accidentally give it two or more, it will complain. Now this isn’t the case with curly braces – if for example you forget an operator somewhere, then your code will compile, and you get unexpected results and potentially a very hard bug to find. Below is contrived (since the expressions are pure and will at least give a warning), but makes the point:
method {
1 +
2
3
}
method(
1 +
2
3
)
The first compiles, the second gives error: ')' expected but integer literal found. The author wanted to write 1 + 2 + 3.
One could argue it’s similar for multi-parameter methods with default arguments; it’s impossible to accidentally forget a comma to separate parameters when using parens.
Verbosity
An important often overlooked note about verbosity. Using curly braces inevitably leads to verbose code since the Scala style guide clearly states that closing curly braces must be on their own line:
… the closing brace is on its own line immediately following the last
line of the function.
Many auto-reformatters, like in IntelliJ, will automatically perform this reformatting for you. So try to stick to using round parens when you can.
Infix Notation
When using infix notation, like List(1,2,3) indexOf (2) you can omit parentheses if there is only one parameter and write it as List(1, 2, 3) indexOf 2. This is not the case of dot-notation.
Note also that when you have a single parameter that is a multi-token expression, like x + 2 or a => a % 2 == 0, you have to use parentheses to indicate the boundaries of the expression.
Tuples
Because you can omit parentheses sometimes, sometimes a tuple needs extra parentheses like in ((1, 2)), and sometimes the outer parentheses can be omitted, like in (1, 2). This may cause confusion.
Function/Partial Function literals with case
Scala has a syntax for function and partial function literals. It looks like this:
{
case pattern if guard => statements
case pattern => statements
}
The only other places where you can use case statements are with the match and catch keywords:
object match {
case pattern if guard => statements
case pattern => statements
}
try {
block
} catch {
case pattern if guard => statements
case pattern => statements
} finally {
block
}
You cannot use case statements in any other context. So, if you want to use case, you need curly braces. In case you are wondering what makes the distinction between a function and partial function literal, the answer is: context. If Scala expects a function, a function you get. If it expects a partial function, you get a partial function. If both are expected, it gives an error about ambiguity.
Expressions and Blocks
Parentheses can be used to make subexpressions. Curly braces can be used to make blocks of code (this is not a function literal, so beware of trying to use it like one). A block of code consists of multiple statements, each of which can be an import statement, a declaration or an expression. It goes like this:
{
import stuff._
statement ; // ; optional at the end of the line
statement ; statement // not optional here
var x = 0 // declaration
while (x < 10) { x += 1 } // stuff
(x % 5) + 1 // expression
}
( expression )
So, if you need declarations, multiple statements, an import or anything like that, you need curly braces. And because an expression is a statement, parentheses may appear inside curly braces. But the interesting thing is that blocks of code are also expressions, so you can use them anywhere inside an expression:
( { var x = 0; while (x < 10) { x += 1}; x } % 5) + 1
So, since expressions are statements, and blocks of codes are expressions, everything below is valid:
1 // literal
(1) // expression
{1} // block of code
({1}) // expression with a block of code
{(1)} // block of code with an expression
({(1)}) // you get the drift...
Where they are not interchangeable
Basically, you can’t replace {} with () or vice versa anywhere else. For example:
while (x < 10) { x += 1 }
This is not a method call, so you can’t write it in any other way. Well, you can put curly braces inside the parentheses for the condition, as well as use parentheses inside the curly braces for the block of code:
while ({x < 10}) { (x += 1) }
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.
There is an effort from the community to standardize the usage of braces and parentheses, see Scala Style Guide (page 21): http://www.codecommit.com/scala-style-guide.pdf
The recommended syntax for higher order methods calls is to always use braces, and to skip the dot:
val filtered = tupleList takeWhile { case (s1, s2) => s1 == s2 }
For "normal" metod calls you should use the dot and parentheses.
val result = myInstance.foo(5, "Hello")
I don't think there is anything particular or complex about curly braces in Scala. To master the seeming-complex usage of them in Scala, just keep a couple of simple things in mind:
curly braces form a block of code, which evaluates to the last line of code (almost all languages do this)
a function if desired can be generated with the block of code (follows rule 1)
curly braces can be omitted for one-line code except for a case clause (Scala choice)
parentheses can be omitted in function call with code block as a parameter (Scala choice)
Let's explain a couple of examples per the above three rules:
val tupleList = List[(String, String)]()
// doesn't compile, violates case clause requirement
val filtered = tupleList.takeWhile( case (s1, s2) => s1 == s2 )
// block of code as a partial function and parentheses omission,
// i.e. tupleList.takeWhile({ case (s1, s2) => s1 == s2 })
val filtered = tupleList.takeWhile{ case (s1, s2) => s1 == s2 }
// curly braces omission, i.e. List(1, 2, 3).reduceLeft({_+_})
List(1, 2, 3).reduceLeft(_+_)
// parentheses omission, i.e. List(1, 2, 3).reduceLeft({_+_})
List(1, 2, 3).reduceLeft{_+_}
// not both though it compiles, because meaning totally changes due to precedence
List(1, 2, 3).reduceLeft _+_ // res1: String => String = <function1>
// curly braces omission, i.e. List(1, 2, 3).foldLeft(0)({_ + _})
List(1, 2, 3).foldLeft(0)(_ + _)
// parentheses omission, i.e. List(1, 2, 3).foldLeft(0)({_ + _})
List(1, 2, 3).foldLeft(0){_ + _}
// block of code and parentheses omission
List(1, 2, 3).foldLeft {0} {_ + _}
// not both though it compiles, because meaning totally changes due to precedence
List(1, 2, 3).foldLeft(0) _ + _
// error: ';' expected but integer literal found.
List(1, 2, 3).foldLeft 0 (_ + _)
def foo(f: Int => Unit) = { println("Entering foo"); f(4) }
// block of code that just evaluates to a value of a function, and parentheses omission
// i.e. foo({ println("Hey"); x => println(x) })
foo { println("Hey"); x => println(x) }
// parentheses omission, i.e. f({x})
def f(x: Int): Int = f {x}
// error: missing arguments for method f
def f(x: Int): Int = f x
I think it is worth explaining their usage in function calls and why various things happen. As someone already said curly braces define a block of code, which is also an expression so can be put where expression is expected and it will be evaluated. When evaluated, its statements are executed and last's statement value is the result of whole block evaluation (somewhat like in Ruby).
Having that we can do things like:
2 + { 3 } // res: Int = 5
val x = { 4 } // res: x: Int = 4
List({1},{2},{3}) // res: List[Int] = List(1,2,3)
Last example is just a function call with three parameters, of which each is evaluated first.
Now to see how it works with function calls let's define simple function that take another function as a parameter.
def foo(f: Int => Unit) = { println("Entering foo"); f(4) }
To call it, we need to pass function that takes one param of type Int, so we can use function literal and pass it to foo:
foo( x => println(x) )
Now as said before we can use block of code in place of an expression so let's use it
foo({ x => println(x) })
What happens here is that code inside {} is evaluated, and the function value is returned as a value of the block evaluation, this value is then passed to foo. This is semantically the same as previous call.
But we can add something more:
foo({ println("Hey"); x => println(x) })
Now our code block contains two statements, and because it is evaluated before foo is executed, what happens is that first "Hey" is printed, then our function is passed to foo, "Entering foo" is printed and lastly "4" is printed.
This looks a bit ugly though and Scala lets us to skip the parenthesis in this case, so we can write:
foo { println("Hey"); x => println(x) }
or
foo { x => println(x) }
That looks much nicer and is equivalent to the former ones. Here still block of code is evaluated first and the result of evaluation (which is x => println(x)) is passed as an argument to foo.
Because you are using case, you are defining a partial function and partial functions require curly braces.
Increased compile checking with parens
The authors of Spray, recommend that round parens give increased compile checking. This is especially important for DSLs like Spray. By using parens you are telling the compiler that it should only be given a single line, therefore if you accidentally gave it two or more, it will complain. Now this isn't the case with curly braces, if for example, you forget an operator somewhere your code will compile, you get unexpected results and potentially a very hard bug to find. Below is contrived (since the expressions are pure and will at least give a warning), but makes the point
method {
1 +
2
3
}
method(
1 +
2
3
)
The first compiles, the second gives error: ')' expected but integer literal found. the author wanted to write 1 + 2 + 3.
One could argue it's similar for multi-parameter methods with default arguments; it's impossible to accidentally forget a comma to separate parameters when using parens.
Verbosity
An important often overlooked note about verbosity. Using curly braces inevitably leads to verbose code since the scala style guide clearly states that closing curly braces must be on their own line: http://docs.scala-lang.org/style/declarations.html "... the closing brace is on its own line immediately following the last line of the function." Many auto-reformatters, like in Intellij, will automatically perform this reformatting for you. So try to stick to using round parens when you can. E.g. List(1, 2, 3).reduceLeft{_ + _} becomes:
List(1, 2, 3).reduceLeft {
_ + _
}
Parenthesis in an ideal coding style is basically used for single line code.
But if the particular piece of code is multiline then using braces is a better way.
With braces, you got semicolon induced for you and parentheses not. Consider takeWhile function, since it expects partial function, only {case xxx => ??? } is valid definition instead of parentheses around case expression.