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?

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

6 Comments

Ah, so c.+= is actually sugar rather than a real function? (don't give it a parameter).
I believe so. When I write c. in an IntelliJ worksheet I'm offered a menu of possible completions, but += is not among them.
I believe the += from implicit resolution.
@marios, I'm not finding it. I tried scalac -Xlog-implicit-conversions test.scala and got no indication of an implicit conversion taking place.
This important little section: scala-lang.org/files/archive/spec/2.12/…
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.