With scala 2.9.2 this code:
BigDecimal(1) + new java.math.BigDecimal("1") new java.math.BigDecimal("1") + BigDecimal(1)
does not compile because scala.math.BigDecimal$#javaBigDecimal2bigDecimal is not applied in the second case
However, if i define the same implicit right before it, the code compiles:
BigDecimal(1) + new java.math.BigDecimal("1") implicit def javaBigDecimal2bigDecimal(x: java.math.BigDecimal): BigDecimal = BigDecimal(x) new java.math.BigDecimal("1") + BigDecimal(1)
Why so?
In first expression BigDecimal(1) + new java.math.BigDecimal("1")
works rule:
Compiler will look for implicits defined within any object of the implicit scope of the type it's looking for.
So, there is a method +(BigDecimal): BigDecimal
on scala.math.BigDecimal
. Compiler sees wrong argument type (java.math.BigDecimal
) and starts to look for conversion to type BigDecimal
. It can't find one in scope, and then it looks in BigDecimal
object and finds javaBigDecimal2bigDecimal
.
Second example will work if there is javaBigDecimal2bigDecimal
conversion in scope because java.math.BigDecimal
doesn't have +
method, and compiler will look for conversion to proper type (which has method +(BigDecimal)
)
Did you import math.BigDecimal._
? For my it works just fine:
Welcome to Scala version 2.9.1.final (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_04).
Type in expressions to have them evaluated.
Type :help for more information.
scala> import math.BigDecimal._
import math.BigDecimal._
scala> import math.BigDecimal
import math.BigDecimal
scala> BigDecimal(1) + new java.math.BigDecimal(1)
res0: scala.math.BigDecimal = 2
edit:
forgot to mention, this works as well:
scala> new java.math.BigDecimal("1") + BigDecimal(1)
res0: scala.math.BigDecimal = 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With