大括号中的奇怪行为与scala中的大括号

时间:2016-08-23 04:19:33

标签: scala

我已经阅读了堆栈溢出中的几个花括号和括号差异,例如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)
  }
}

1 个答案:

答案 0 :(得分:4)

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

from collections import OrderedDict

def first_unique_char(string):
    duplicated = OrderedDict()  # ordered dict of char to boolean indicating duplicate existence
    for s in string:
        duplicated[s] = s in duplicated

    for char, is_duplicate in duplicated.items():
        if not is_duplicate:
            return string.find(char)
    return -1

print(first_unique_char('timecomplexity'))  # 4

你只能有一个表达式。所以,像:

...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中的范围,

{}