4

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?

allidoiswin
  • 2,543
  • 1
  • 20
  • 23

2 Answers2

10

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.

Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653
2

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.

jwvh
  • 50,871
  • 7
  • 38
  • 64
  • Ah, so c.+= is actually sugar rather than a real function? (don't give it a parameter). – allidoiswin Jan 21 '17 at 00:08
  • I believe so. When I write `c.` in an IntelliJ worksheet I'm offered a menu of possible completions, but `+=` is not among them. – jwvh Jan 21 '17 at 00:15
  • I believe the `+=` from implicit resolution. – marios Jan 21 '17 at 02:39
  • @marios, I'm not finding it. I tried `scalac -Xlog-implicit-conversions test.scala` and got no indication of an implicit conversion taking place. – jwvh Jan 21 '17 at 03:06
  • @jwvh you are right. It seems that scala in injecting a synthetic method at runtime to cover this case. The best reason I can see for doing that is to avoid boxing altogether. Maybe – marios Jan 21 '17 at 04:56
  • 2
    This important little section: http://www.scala-lang.org/files/archive/spec/2.12/06-expressions.html#assignment-operators – som-snytt Jan 21 '17 at 06:55