0

I've read through several curly braces and braces differences in stackoverflow, such as What is the formal difference in Scala between braces and parentheses, and when should they be used?, but I didn't find the answer for my following question

object Test {
  def main(args: Array[String]) {
    val m = Map("foo" -> 3, "bar" -> 4)
    val m2 = m.map(x => {
      val y = x._2 + 1
      "(" + y.toString + ")" 
    })

    // The following DOES NOT work
    // m.map(x =>
    //   val y = x._2 + 1
    //   "(" + y.toString + ")"
    // )
    println(m2)

    // The following works
    // If you explain {} as a block, and inside the block is a function
    // m.map will take a function, how does this function take 2 lines?
    val m3 = m.map { x => 
      val y = x._2 + 2         // this line
      "(" + y.toString + ")"   // and this line they both belong to the same function
    }
    println(m3)
  }
}
Community
  • 1
  • 1
user534498
  • 3,926
  • 5
  • 27
  • 52

1 Answers1

4

The answer is very simple, when you use something like:

...map(x => x + 1) 

You can only have one expression. So, something like:

scala> List(1,2).map(x => val y = x + 1; y)
<console>:1: error: illegal start of simple expression
List(1,2).map(x => val y = x + 1; y)
...

Simply doesn't work. Now, let's contrast this with:

scala> List(1,2).map{x => val y = x + 1; y} // or
scala> List(1,2).map(x => { val y = x + 1; y })
res4: List[Int] = List(2, 3)

And going even a little further:

scala> 1 + 3 + 4
res8: Int = 8

scala> {val y = 1 + 3; y}  + 4
res9: Int = 8

Btw, the last y never left the scope in the {},

scala> y
<console>:18: error: not found: value y
pedrofurla
  • 12,763
  • 1
  • 38
  • 49
  • So it means that for function takes x as argument, if using {}, everything after x => and before the closing }, including multiple lines, belongs to this function? It's just not that intuitive comparing to java/c style of grammer parsing. – user534498 Aug 23 '16 at 05:38
  • 2
    The same is actually true for Java and C. {} delimits a scope, you can put code in a {} block in both Java and C for example to reduce the lifetime of variables. In Java 8, lambdas can be single line without {}, or multiline with {}, so exactly the same as in Scala. – drexin Aug 23 '16 at 06:23