为什么 Scala 语言中的 ++: 运算符如此奇怪?

Why is the ++: operator in the Scala language so strange?

我正在使用++:运算符获取两个集合的集合,但是我使用这两种方法得到的结果不一致:

scala> var r = Array(1, 2)
r: Array[Int] = Array(1, 2)
scala> r ++:= Array(3)
scala> r
res28: Array[Int] = Array(3, 1, 2)

scala> Array(1, 2) ++: Array(3)
res29: Array[Int] = Array(1, 2, 3)

为什么 ++:++:= 运算符给出不同的结果? ++运算符不会出现这种差异。

我使用的Scala版本是2.11.8。

因为它以冒号结尾,所以 ++: 是右结合的。这意味着 Array(1, 2) ++: Array(3) 等同于 Array(3).++:(Array(1, 2))++: 可以认为是 "prepend the elements of the left array to the right array."

由于它是右结合的,r ++:= Array(3) 脱糖为 r = Array(3) ++: r。当您认为 ++: 的目的是前置时,这是有道理的。这种脱糖适用于任何以冒号结尾的运算符。

如果要附加,可以使用++(和++=)。

这里冒号(:)表示函数有右结合性

所以,例如 coll1 ++: coll2 类似于 (coll2).++:(coll1)

这通常意味着左集合的元素被添加到右集合中

案例一:

Array(1,2) ++: Array(3)
Array(3).++:Array(1,2) 
Elements of the left array is prepended to the right array 
so the result would be Array(3,1,2)

案例 2:

 r = Array(1,2)
 r ++:= Array(3) //This could also be written as the line of code below
 r = Array(3) ++: r
   = r. ++: Array(3)
   = Array(1,2). ++: Array(3) //Elements of the left array is prepended to the right array 
 so their result would be Array(1,2,3)

希望这能解决问题 谢谢 :)