This simple test, of course, works as expected:
scala> var b = 2 b: Int = 2 scala> b += 1 scala> b res3: Int = 3
Now I bring this into scope:
class A(var x: Int) { def +=(y:Int) { this.x += y } } implicit def int2A(i:Int) : A = new A(i)
I'm defining a new class and a += operation on it, and a convenient implicit conversion for those times when I want to add an Int to A's Int value.
I never expected this would affect the way my regular Int operations behave, when the "A" class is not at all part of the expression.
But it does:
scala> var b:Int = 0 b: Int = 0 scala> b += 1 scala> b res29: Int = 0 scala> b += 2 scala> b res31: Int = 0
What seems to be happening here is that the b:Int is implicitly converted to an "A", which is not bound to any variable, and then += is invoked on it, discarding the results.
Scala seems to give high precedence the implicit conversion over the natural += behavior (compiler magic, not an actual method) that is already defined to Ints. Common-sense as well as a C++ background tells me implicits should only be invoked as a last resort, when the compilation would otherwise fail. That leads to several questions...
Thanks
Even withstanding Eastsun's explanation, it seems like this is a bug, and it should try the b=b+1
transformation before trying an implicit conversion for +=
.
Please ask this question to the scala-user email list by emailing [email protected] or by visiting n4.nabble.com/Scala-User-f1934582.html. If it's a bug, that's where it will be noticed and fixed.