Scala:“:=”做什么和“::=”运营商做什么?
我对 scala 很陌生。我浏览了一下这本书,在代码中偶然发现了这两个运算符。他们做什么?
I'm pretty new with scala. I skimmed through the book and stumbled these two operators in code. What do they do ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
语法糖
在 Scala 中使用运算符时,存在一些适用的语法糖。
考虑一个运算符
*
。当编译器遇到a *= b
时,会检查a
上是否定义了方法*=
,并调用a.*= (b)如果可能的话。否则表达式将扩展为
a = a.*(b)
。但是,任何以
:
结尾的运算符在转换为方法调用时都会交换左右参数。因此,a :: b
变为b.::(a)
。另一方面,a ::= b
变为a = a.::(b)
,由于缺乏顺序反转,这可能是违反直觉的。由于特殊含义,无法定义运算符
:
。因此:
与其他符号结合使用,例如:=
。运算符的含义
Scala 中的运算符是由库编写者定义的,因此它们可以表示不同的含义。
::
运算符通常用于列表连接,a ::= b
表示取 a,在其前面添加 b,并将结果赋给 a.
a := b
通常意味着将 a 的值设置为 b 的值
,而不是a = b
,后者会导致引用 a 指向对象 b
。Syntactic Sugar
There is some syntactic sugar that applies when using operators in Scala.
Consider an operator
*
. When compiler encountersa *= b
, it will check if method*=
is defined ona
, and calla.*=(b)
if possible. Otherwise the expression will expand intoa = a.*(b)
.However, any operator that ends with a
:
will have the right and left arguments swapped when converting to method invocation. Soa :: b
becomesb.::(a)
. On the other handa ::= b
becomesa = a.::(b)
which could be counter-intuitive due to the lack of the order reversal.Because of the special meaning, it is not possible to define an operator
:
. So:
is used in conjunction with other symbols, for example:=
.Meaning of Operators
Operators in Scala are defined by the library writers, so they can mean different things.
::
operator is usually used for list concatenation, anda ::= b
meanstake a, prepend b to it, and assign the result to a
.a := b
usually meansset the value of a to the value of b
, as opposed toa = b
which will causethe reference a to point to object b
.这将调用左侧对象上的方法
:
或::
,并以右侧对象作为参数,并将结果分配给变量 at左手边。相当于
查看对象类型的
:
或::
方法的文档。(对于集合,
::
方法将一个元素附加到列表的开头。)This calls the method
:
or::
on the object at the left hand side, with the object at the right hand side as argument, and assigns the result to the variable at the left hand side.Is equivalent to
See the documentation for the
:
or::
method of the object's type.(For collections, the
::
method appends an element to the beginning of the list.)