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)
}
}
因此,這意味着對於函數,以x爲參數,如果使用{},則在x =>之後和結束之前的所有內容都包含多行,屬於此函數?這與java/c風格的語法分析相比並不那麼直觀。 – user534498
對於Java和C,情況也是如此。{}劃定範圍,您可以將代碼放在Java和C中的塊中,以減少變量的生存期。在Java 8中,lambda可以是沒有{}的單行,也可以是{}的多行,這與Scala中的完全相同。 – drexin