user534498 user534498 - 3 months ago 15
Scala Question

Strange behaviour in curly braces vs braces in scala

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)
}
}

Answer

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
Comments