隐含点和括号的Scala优先级

时间:2012-09-27 14:08:43

标签: scala operator-precedence

以下“括号”如何?

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 ", ")

1 个答案:

答案 0 :(得分:4)

以字母开头的运算符具有最低优先级。 +优先级较低,但高于mapmkString。所以

"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