Why is there an implicit conversion from Float / Double to BigDecimal, but not from String?

Although the conversion from Double to BigDecimal 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) 

works very well, it would be wise to have an implicit conversion like

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

available by default, which can convert strings to BigDecimals as follows:

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

Or am I missing something, and Scala resolved all Java “problems” using the BigDecimal constructor with a floating point value instead of String , and BigDecimal(String) no longer needed in Scala?

+6
floating-point scala implicit bigdecimal
source share
2 answers

It was a thought , but apparently a pullback because it created ambiguous transformations. See this thread in scala -list .

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

If you still want the local string2BigDecimal implicit for your personal use:

  • rules for the implicit scope can be found in the specification, §7.2,
  • to eliminate the ambiguity in favor of your string2BigDecimal , you must define it using a subclass, see this article (§6.5) for an example and this one (§ Avoiding ambiguities) for an explanation.
+8
source share

Because BigDecimal can always be created from Double or Float , but not always from a string. In general, it is a good idea that when something has this “property” to use explicit implicit. For example, this would be good:

 "1.23".toBigDecimal 
+2
source share

All Articles