Curly braces are the way Scala uses to glue together a group of expressions into one whose result is the result of the last expression in the block.
e.g:
{
val x = 3
x*2
}
Is an expression whose result is 6
.
Writing a single expression within curly braces is redundant and would only make sense for aesthetic purposes.
Going back to your pattern matching:
ints match {
case Nil => 0
}
Is an expression as any other so you can write it within curly braces or not.
{
ints match {
case Nil => 0
}
}
Scala lets you define your methods body as a group of expressions:
def methodName(params...) { exp0; exp1; .., resExp } // Return type will be Unit.
NOTE That Scala's type inference will determine methodName
return type as Unit
.
Or as =
with an expression at its right side, which could also be a group of expressions this way glued by curly braces.
def methodName(params...): Type = expression
def methodName(params...) = expression //Return type will be the expression's type.
So you can write it in these 3 forms:
// `=` with a single expression at is right side.
def sum(ints: List[Int]): Int = ints match {
case Nil => 0
}
// `=` with a glued sequence of expressions at is right side.
def sum(ints: List[Int]): Int = {
ints match {
case Nil => 0
}
}
// A glued sequence of expressions at is right side, but its return type will be Unit!
def sum(ints: List[Int]) {
ints match {
case Nil => 0
}
}