以下“括号”如何?
val words = List("foo", "bar", "baz")
val phrase = "These are upper case: " + words map { _.toUpperCase } mkString ", "
与
相同val words = List("foo", "bar", "baz")
val phrase = "These are upper case: " + words.map(_.toUpperCase).mkString(", ")
换句话说,隐含的点(“。”)和括号是否与实际的优先级相同?
第一个版本是否与
相同val words = List("foo", "bar", "baz")
val phrase =
"These are upper case: " + (words map { _.toUpperCase } mkString ", ")
答案 0 :(得分:4)
以字母开头的运算符具有最低优先级。 +
优先级较低,但高于map
或mkString
。所以
"These are upper case: " + words map { _.toUpperCase } mkString ", "
应解析为:
(("These are upper case: " + words).map{ _.toUpperCase }).mkString(", ")
将其视为:
v1 + v2 map v3 mkString v4
((v1 + v2) map v3) mkString v4
有关详细信息,请参阅我的其他答案:When to use parenthesis in Scala infix notation