16

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.

Daniel Langdon
  • 5,899
  • 4
  • 28
  • 48

1 Answers1

14

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

Arne Claassen
  • 14,088
  • 5
  • 67
  • 106
  • You answer is great and I've found my answers. However, since it's an important question for beginners and many others may also look at it. Could you please correct some typos in the answer? Thanks – Max Wong Apr 27 '20 at 02:09