Scala: why do I have to put extra parenthesis here

2019-08-05 01:50发布

问题:

Are the parenthesis around the final tuple really needed? It doesn't compile without them and the compiler tries to add only the Sort("time") and complains that it expects a tuple instead.

val maxSortCounts: Map[Sort, Int] =
  sorts.map(s => s -> usedPredicates.map(pred => pred.signature.count(_ == s)).max)
    .toMap + ((Sort("time"), 1))

I've tried to reproduce this behaviour inside the REPL with a shorter example, but there it behaves as intended. The variable sorts is a Seq[Sort].

error: type mismatch;
found   : <snip>.Sort
required: (<snip>.Sort, Int)
.toMap + (Sort("time"), 1)

回答1:

Yes, they are needed. Otherwise the compiler will interpret the code as x.+(y, z) instead of x.+((y, z)).

Instead, you can use ArrowAssoc again: x + (y -> z). Notice, the parentheses are also needed because + and - have the same precedence (only the first sign of a method defines its precedence).



回答2:

Yes, they're needed. They make the expression a tuple. Parentheses surrounding a comma-separated list create tuple objects. For example, (1, 2, 3) is a 3-tuple of numbers.

Map's + method accepts a pair - in other words a tuple of two elements. Map represents entries in the map as (key,value) tuples.