Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why javaBigDecimal2bigDecimal implicit is not applicable?

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?

like image 280
OlegYch Avatar asked Feb 20 '23 14:02

OlegYch


2 Answers

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))

like image 155
4e6 Avatar answered Feb 23 '23 20:02

4e6


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
like image 36
drexin Avatar answered Feb 23 '23 19:02

drexin