3

Is +=(or any assignment operators) a method in scala for Int type.

For example,

var x=5 x+=1 

Here I am able to use += method only when it is a variable.

I am not able to do,

5+=1 

Does scala compiler considers this method as a special case?

Why it is not available in scala.Int class?

3
  • What do you expect 5+=1 to actually do? I don't know Scala, but I don't see any reason for it to allow you to overwrite a primitive's value... Commented Apr 29, 2016 at 12:05
  • I thought there is no operator in scala(only methods), so there will not be a difference between value and variable. Commented Apr 29, 2016 at 12:09
  • 5.+(1) and x.+(1) will work consistently, so I expect this operator to behave in the same way. Commented Apr 29, 2016 at 12:11

1 Answer 1

11

There is no += method, it is expanded to x = x + 1 by the compiler. This is detailed in the specification:

6.12.4 Assignment Operators

Let's consider an assignment operator such as += in an infix operation l += r, where l, r

are expressions. This operation can be re-interpreted as an operation which corresponds to the assignment

l = l + r 

except that the operation's left-hand-side l is evaluated only once.

The re-interpretation occurs if the following two conditions are fulfilled.

  1. The left-hand-side l does not have a member named +=, and also cannot be converted by an implicit conversion to a value with a member named +=.

  2. The assignment l = l + r is type-correct. In particular this implies that l refers to a variable or object that can be assigned to, and that is convertible to a value with a member named +.

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

2 Comments

So you could do this for any method that fulfills the condition? E.g. obj1 concat= obj2?
@LukaJacobowitz - I don't think so, this only applies to operators which are lexically non-empty sequences of operator characters. The lexical syntax section defines operator chars as printable ascii characters which are not whitespace, letters, digits, parenthesis or delimiters.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.