Json.obj Scala, string concat: Compilation error

This is easily explained by looking at operator precedence.

From the language reference http://scala-lang.org/files/archive/spec/2.11/06-expressions.html#infix-operations, we can see that operators + and -> have the same precedence. This is because, in general, it is the first character of an operator that determines its precedence. In our case, the first characters are + and -, which both have the same precedence.

thus, writing "code" -> "this mode " + str + " does not exist" is the same as writing:

"code"
  .->("this mode ")
  .+(str)
  .+(" does not exist")

This is consistent with what the compiler tells you:

  • the result type of the first operation ("code" -> "this mode ") is (String, String) which is equivalent to Tuple2[String, String]
  • (String, String) + String triggers an implicit toString() conversion on the tuple, therefore the resulting type is String.

You seem to have already found the better way to format it in a more readable way.

As to other cases were parentheses are needed, the obvious answer would be that you need them as soon as you don't want what the behavior that operator precedence would give you. As such I highly recommend reading chapter 6.12 of the spec linked above!