1

Consider the following two declarations:

var x: Int = 0
val y: Int = 0

x is a variable whereas y is a value, both of the same type: Int.

I can use += on x:

x += 1
x.+=(1)

However, if I try to use += on y, I get a compile-time error — "Not Found Error" (E008) — with the description:

+= is not a member of Int

I understand that y is immutable because it's a value, and this behavior is desirable.

What mechanism does Scala use to provide x and y with different methods taking into account that they are both of type Int?

JFMR
  • 23,265
  • 4
  • 52
  • 76
  • 3
    If there is no `def +=` on your type `X` (in `scala.Int` there isn't) Scala tries to rewrite code into `x1 = x1.+(x2)`. This requires only existence of `+` operator with matching type AND availability of `=` assignment. `var` has it available, `val` doesn't. You can see it in user defined types in scastie: https://scastie.scala-lang.org/mIj1tJgmQ1Ocp5vCeRA58g – Mateusz Kubuszok Apr 13 '23 at 19:57
  • Thank you @MateuszKubuszok if you could make your comment into an answer, I would accept it. – JFMR Apr 20 '23 at 18:15

0 Answers0