Just starting out with Scala
var c = 0
c += 1
works
c.+=
gives me error: value += is not a member of Int
Where is the +=
defined?
Just starting out with Scala
var c = 0
c += 1
works
c.+=
gives me error: value += is not a member of Int
Where is the +=
defined?
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
has a member named ω=
or is implicitly convertible to an object that has a member named ω=
.
Otherwise, it gets desugared to
l = l.ω(r)
(except l
is guaranteed to be only evaluated once), if that typechecks.
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.
Actually, the code you've described does work.
scala> var c = 4
c: Int = 4
scala> c.+=(2) // no output because assignment is not an expression
scala> c
res1: Int = 6
I suspect (but can't say for sure) that it can't be found in the library because the compiler de-surgars (rewrites) it to c = c.+(1)
, which is in the library.