2016-08-23 66 views
0

我通過幾個大括號閱讀和拉桿在計算器的差異,如What is the formal difference in Scala between braces and parentheses, and when should they be used?,但我沒有找到答案了我的以下問題奇怪的行爲在大括號VS在斯卡拉大括號

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

回答

3

的答案很簡單,當你使用類似的東西時:

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

你只能有一個表達式。所以,像這樣:

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

只是不起作用。現在,讓我們用對比的:

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) 

中去,甚至再遠一點:

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

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

順便說一句,最後y從未在{}留下的範圍,

scala> y 
<console>:18: error: not found: value y 
+0

因此,這意味着對於函數,以x爲參數,如果使用{},則在x =>之後和結束之前的所有內容都包含多行,屬於此函數?這與java/c風格的語法分析相比並不那麼直觀。 – user534498

+1

對於Java和C,情況也是如此。{}劃定範圍,您可以將代碼放在Java和C中的塊中,以減少變量的生存期。在Java 8中,lambda可以是沒有{}的單行,也可以是{}的多行,這與Scala中的完全相同。 – drexin