Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Omitting curly braces in scala for multiple lines

Tags:

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.

like image 510
Daniel Langdon Avatar asked Sep 24 '15 15:09

Daniel Langdon


1 Answers

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

like image 198
Arne Claassen Avatar answered Nov 16 '22 01:11

Arne Claassen