Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where is Scala's += defined in the context of Int?

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?

like image 680
allidoiswin Avatar asked Oct 25 '25 14:10

allidoiswin


2 Answers

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.

like image 157
Jörg W Mittag Avatar answered Oct 28 '25 02:10

Jörg W Mittag


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.

like image 28
jwvh Avatar answered Oct 28 '25 03:10

jwvh