7

Although the situation of conversion from Doubles to BigDecimals has improved a bit compared to Java

scala> new java.math.BigDecimal(0.2)
res0: java.math.BigDecimal = 0.20000000000000001110223024625156...

scala> BigDecimal(0.2)
res1: scala.math.BigDecimal = 0.2

and things like

val numbers: List[BigDecimal] = List(1.2, 3.2, 0.7, 0.8, 1.1)

work really well, wouldn't it be reasonable to have an implicit conversion like

implicit def String2BigDecimal(s: String) = BigDecimal(s)

available by default which can convert Strings to BigDecimals like this?

val numbers: List[BigDecimal] = List("1.2", "3.2", "0.7", "0.8", "1.1")

Or am I missing something and Scala resolved all "problems" of Java with using the BigDecimal constructor with a floating point value instead of a String, and BigDecimal(String) is basically not needed anymore in Scala?

Dave Griffith
  • 20,435
  • 3
  • 55
  • 76
soc
  • 27,983
  • 20
  • 111
  • 215
  • This has little to do with the Java language itself, why should it be tagged "Java"? – MAK Jan 16 '11 at 13:05

2 Answers2

8

This was thought of, but apparently rolled back because it created ambiguous conversions. See this thread on the scala-list.

The thread is old, but as far as I can see, string2Bigdecimal is still not defined as an implicit.

If you still want to have a local string2BigDecimal implicit for your personal use:

  • the rules for implicit scope can be found in the specification, §7.2,
  • to resolve ambiguities in favor of your string2BigDecimal, you should define it using subclassing, see this paper (§6.5) for an example, and this oneAvoiding Ambiguities) for an explanation.
Francois G
  • 11,957
  • 54
  • 59
  • This is happened quite some time ago. I remember that there was something about being able to define a "precedence" of implicits with inheritance in the mean time. Wouldn't that work here? Or is this something completely different? – soc Jan 16 '11 at 12:02
3

Because a BigDecimal can always be created from a Double or a Float, but not always from a String. In general, it is a good idea that, where something has this "property" to use an explicit implicit. For example, this would be nice:

"1.23".toBigDecimal
oxbow_lakes
  • 133,303
  • 56
  • 317
  • 449
  • Yes, that is certainly a valid concern, and the recommendations of [this previous question](http://stackoverflow.com/questions/1404889/scala-implicit-usage-choices) certainly apply to having a toplevel `string2BigDecimal` implicit. – Francois G Jan 16 '11 at 22:43