Scala 的 += 在 Int 的上下文中定义在哪里? [英] Where is Scala's += defined in the context of Int?

查看:51
本文介绍了Scala 的 += 在 Int 的上下文中定义在哪里?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

刚开始使用 Scala
var c = 0
c += 1 有效
c.+= 给我 error: value += is not a member of Int

Just starting out with Scala
var c = 0
c += 1 works
c.+= gives me error: value += is not a member of Int

+= 在哪里定义的?

推荐答案

Scala 语言规范 (SLS) 的第 6.12.4 节赋值运算符解释了如何对此类复合赋值运算符进行脱糖:

Section 6.12.4 Assignment Operators of the Scala Language Specification (SLS) explains how such compound assignment operators are desugared:

l ω= r

(其中 ω 是除 <>! 和不以 = 开头)被脱糖为

(where ω is any sequence of operator characters other than <, >, ! and doesn't start with =) gets desugared to

l.ω=(r)

IFF l 具有名为 ω= 的成员,或者可以隐式转换为具有名为 ω=<的成员的对象/代码>.

IFF l has a member named ω= or is implicitly convertible to an object that has a member named ω=.

否则,它会被脱糖

l = l.ω(r)

(除了 l 保证只被评估一次),如果类型检查.

(except l is guaranteed to be only evaluated once), if that typechecks.

或者,更简单地说:编译器将首先尝试 l.ω=(r),如果这不起作用,它将尝试 l = l.ω(r).

Or, to put it more simply: the compiler will first try l.ω=(r) and if that doesn't work, it will try l = l.ω(r).

这允许诸如 += 之类的东西像在其他语言中一样工作,但仍然被覆盖以做不同的事情.

This allows something like += to work like it does in other languages but still be overridden to do something different.

这篇关于Scala 的 += 在 Int 的上下文中定义在哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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