Scala puts precedence on implicit conversion over "natural" operations... Why? Is this a bug? Or am

Posted by Alex R on Stack Overflow See other posts from Stack Overflow or by Alex R
Published on 2010-04-21T13:00:50Z Indexed on 2010/04/21 13:03 UTC
Read the original article Hit count: 132

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.

I never expected this would affect the way my regular Ints behave.

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

Scala seems to prefer the implicit conversion over the natural += that is already defined to Ints. That leads to several questions...

  • Why? Is this a bug? Is it by design?
  • Is there a work-around (other than not using "+=")?

Thanks

© Stack Overflow or respective owner

Related posts about scala

Related posts about scala-2.8