为什么 Scala 中的对象表示法显然消除了以“:”结尾的方法的右侧关联性?

Why does object notation in Scala apparently eliminate the right side associativity of methods ending in ':'?

我目前正在学习 Scala,想知道在调用以“:”结尾的方法时使用对象表示法的区别。 由于以“:”结尾的方法名称通常会产生右侧关联性,因此在使用对象表示法调用此类方法时,这似乎会发生变化。

示例:

scala> 3 +: List(1,2) 
res1: List[Int] = List(3, 1, 2) 

scala> List(1,2) +: 3 // does not compile due to right side associativity

scala> (List(1,2)).+:(3) 
res2: List[Int] = List( 3, 1, 2)

现在我不明白为什么使用对象表示法会禁用右关联性功能。有人可以解释这个或 link 到关于这个问题的文档吗?

来自 the spec、"Infix Operations":

The associativity of an operator is determined by the operator's last character. Operators ending in a colon `:' are right-associative. All other operators are left-associative.

方法 +: 在列表中定义,这就是 (List(1,2)).+:(3) 起作用的原因。它的实现是元素放在最前面,所以等同于3 :: List(1, 2),但这里无关紧要。

使用 infix 符号 List(1,2) +: 3 将不起作用,因为(如规范中所述)所有以冒号结尾的中缀运算符都是 right-associative,这意味着 "right hand side" 使用带有 "left hand side" 作为参数的运算符,而不是 vice-versa。

基本上,

1 +: 2 +: 3 +: List(4, 5) 

List(4, 5).+:(3).+:(2).+:(1)

具有相同的效果(我知道这在你的问题中已经很明显了,但我只是强调 right-associativity)。

所以,用一个简单的句子来回答你的问题:并不是说 right-side 关联性在对象表示法中被 移除,而是 在中缀表示法中添加了,但仅适用于以冒号结尾的方法。