Scala:“:=”做什么和“::=”运营商做什么?

发布于 2024-12-02 16:43:06 字数 52 浏览 5 评论 0原文

我对 scala 很陌生。我浏览了一下这本书,在代码中偶然发现了这两个运算符。他们做什么?

I'm pretty new with scala. I skimmed through the book and stumbled these two operators in code. What do they do ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

静待花开 2024-12-09 16:43:06

语法糖

在 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 encounters a *= b, it will check if method *= is defined on a, and call a.*=(b) if possible. Otherwise the expression will expand into a = a.*(b).

However, any operator that ends with a : will have the right and left arguments swapped when converting to method invocation. So a :: b becomes b.::(a). On the other hand a ::= b becomes a = 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, and a ::= b means take a, prepend b to it, and assign the result to a.

a := b usually means set the value of a to the value of b, as opposed to a = b which will cause the reference a to point to object b.

爺獨霸怡葒院 2024-12-09 16:43:06

这将调用左侧对象上的方法 ::: ,并以右侧对象作为参数,并将结果分配给变量 at左手边。

foo ::= bar

相当于

foo = foo.::(bar)

查看对象类型的 ::: 方法的文档。

(对于集合,:: 方法将一个元素附加到列表的开头。)

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.

foo ::= bar

Is equivalent to

foo = foo.::(bar)

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.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文