Ralph
Ralph

Reputation: 32304

Scala precedence of implied dots and parentheses

How is the following "parenthesized"?

val words = List("foo", "bar", "baz")
val phrase = "These are upper case: " + words map { _.toUpperCase } mkString ", "

Is it the same as

val words = List("foo", "bar", "baz")
val phrase = "These are upper case: " + words.map(_.toUpperCase).mkString(", ")

In other words, do implied dots (".") and parentheses have the same precedence as the real ones?

Is the first version the same as

val words = List("foo", "bar", "baz")
val phrase =
  "These are upper case: " + (words map { _.toUpperCase } mkString ", ")

Upvotes: 3

Views: 214

Answers (1)

huynhjl
huynhjl

Reputation: 41646

Operators starting with letters have the lowest precedence. + has low precedence but higher than map or mkString. So

"These are upper case: " + words map { _.toUpperCase } mkString ", "

should be parsed as:

(("These are upper case: " + words).map{ _.toUpperCase }).mkString(", ")

Think of it as:

v1 + v2 map v3 mkString v4
((v1 + v2) map v3) mkString v4

See my other answer for more info: When to use parenthesis in Scala infix notation

Upvotes: 4

Related Questions