Scala:为什么我必须在这里添加额外的括号?
最终元组周围的括号真的需要吗?如果没有它们,它就无法编译,并且编译器尝试仅添加 Sort("time") 并抱怨它需要一个元组。
val maxSortCounts: Map[Sort, Int] =
sorts.map(s => s -> usedPredicates.map(pred => pred.signature.count(_ == s)).max)
.toMap + ((Sort("time"), 1))
我尝试用一个较短的示例在 REPL 中重现此行为,但它的行为符合预期。变量sorts
是一个Seq[Sort]
。
error: type mismatch;
found : <snip>.Sort
required: (<snip>.Sort, Int)
.toMap + (Sort("time"), 1)
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,他们是需要的。否则编译器会将代码解释为
x.+(y, z)
而不是x.+((y, z))
。相反,您可以再次使用 ArrowAssoc:
x + (y -> z)
。请注意,还需要括号,因为+
和-
具有相同的优先级(只有方法的第一个符号定义其优先级)。Yes, they are needed. Otherwise the compiler will interpret the code as
x.+(y, z)
instead ofx.+((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).是的,他们是需要的。他们使表达式成为一个元组。逗号分隔列表周围的括号创建元组对象。例如,
(1, 2, 3)
是一个三元组数字。Map
的+
方法接受一对 - 换句话说,两个元素的元组。 Map 将映射中的条目表示为(key,value)
元组。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.