为什么存在从 Float/Double 到 BigDecimal 的隐式转换,而不是从 String 的隐式转换?
虽然从 Double 到 BigDecimal 的转换情况与 Java 相比已经有所改善
scala> new java.math.BigDecimal(0.2)
res0: java.math.BigDecimal = 0.20000000000000001110223024625156...
scala> BigDecimal(0.2)
res1: scala.math.BigDecimal = 0.2
,并且
val numbers: List[BigDecimal] = List(1.2, 3.2, 0.7, 0.8, 1.1)
工作得很好,但是进行隐式转换不是合理的吗就像
implicit def String2BigDecimal(s: String) = BigDecimal(s)
默认情况下可用的那样,它可以像这样将字符串转换为 BigDecimals 吗?
val numbers: List[BigDecimal] = List("1.2", "3.2", "0.7", "0.8", "1.1")
或者我是否遗漏了一些东西,Scala 通过使用具有浮点值而不是 String 的 BigDecimal 构造函数解决了 Java 的所有“问题”,并且 BigDecimal(String ) 在 Scala 中基本上不再需要了?
Although the situation of conversion from Double
s to BigDecimal
s 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是想法,但显然回滚,因为它创建了不明确的转换。请参阅scala-list 上的此线程。
该线程很旧,但据我所知, string2Bigdecimal 是 仍未定义为隐式。
如果您仍然希望有一个本地
string2BigDecimal
隐式供您个人使用:string2BigDecimal
的歧义。 code>,您应该使用子类来定义它,请参阅本文(§6.5) 为例,这个(§避免歧义)以获得解释。
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:string2BigDecimal
, you should define it using subclassing, see this paper(§6.5) for an example, and this one (§ Avoiding Ambiguities) for an explanation.
因为
BigDecimal
总是可以从Double
或Float
创建,但并不总是来自字符串的strong>。一般来说,如果某物具有此“属性”,则使用显式隐式是一个好主意。例如,这会很好:Because a
BigDecimal
can always be created from aDouble
or aFloat
, 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: