【问题标题】:Strange behaviour in curly braces vs braces in scala花括号中的奇怪行为与scala中的大括号
【发布时间】:2016-12-29 18:11:37
【问题描述】:

我已经阅读了stackoverflow中的几个大括号和大括号的差异,例如What is the formal difference in Scala between braces and parentheses, and when should they be used?,但我没有找到我以下问题的答案

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

【问题讨论】:

    标签: scala


    【解决方案1】:

    答案很简单,当你使用类似的东西时:

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

    【讨论】:

    • 也就是说for函数以x为参数,如果使用{},x=>之后和结束}之前的所有内容,包括多行,都属于这个函数吗?与语法分析的 java/c 风格相比,它并不那么直观。
    • Java 和 C 实际上也是如此。{} 界定了一个范围,您可以将代码放在 Java 和 C 中的 {} 块中,例如减少变量的生命周期。在 Java 8 中,lambda 可以是不带 {} 的单行,也可以是带 {} 的多行,因此与 Scala 中的完全相同。
    猜你喜欢
    • 2012-12-17
    • 1970-01-01
    • 1970-01-01
    • 2019-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多