为什么Scala语言中的++:运算符如此奇怪? [英] Why is the ++: operator in the Scala language so strange?

查看:88
本文介绍了为什么Scala语言中的++:运算符如此奇怪?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using the ++: operator to get a collection of two collections, but the results I get using these two methods are inconsistent:

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)

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

Why do the ++: and ++:= operators give different results? This kind of difference does not appear with the ++ operator.

我正在使用的Scala版本是2.11.8.

The version of Scala I am using is 2.11.8.

推荐答案

由于它以冒号结尾,因此++:是右关联的.这意味着Array(1, 2) ++: Array(3)等同于Array(3).++:(Array(1, 2)). ++:可以被认为是将左数组的元素添加到右数组的前面."

Since it ends in a colon, ++: is right-associative. This means that Array(1, 2) ++: Array(3) is equivalent to Array(3).++:(Array(1, 2)). ++: can be thought of as "prepend the elements of the left array to the right array."

由于它是右关联的,所以r ++:= Array(3)减少了对r = Array(3) ++: r的影响.当您认为++:的目的是前置的时,这是有道理的.对于任何以冒号结尾的运算符,这种减法都是适用的.

Since it's right-associative, r ++:= Array(3) desugars to r = Array(3) ++: r. This makes sense when you consider that the purpose of ++: is prepending. This desugaring holds true for any operator that ends in a colon.

如果要追加,可以使用++(和++=).

If you want to append, you can use ++ (and ++=).

这篇关于为什么Scala语言中的++:运算符如此奇怪?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆