如何在纯 Scala 中表示盒装 Double?
在 Scala 中,双精度数字有两种表示形式,一种是 AnyVal
,另一种是 AnyRef
。在 JVM 上,它们分别映射到原语 double
和类 java.lang.Double
。
现在在 JVM 以外的平台上会发生什么?我可以使用 Scala.Double 作为原语,但如何指定我想要对装箱 Double 的引用而不指定 java.lang.Double?
[上下文 - 留下来理解托马斯的回答,但不是根本问题。
我有一个 Double,我想用 Spring 将其注入到 Wicket 组件中:
class MyPanel(id: String) extends Panel(id) {
@SpringBean(name="rxAlarmLimitDb") var alarmLimitDb: Double = _
如果我将类型指定为 scala.Double ,如上所述,注入器会失败,因为它只能注入对象。
如果我指定 java.lang.Double 作为字段的类型,一切都很好
class MyPanel(id: String) extends Panel(id) {
@SpringBean(name="rxAlarmLimitDb") var alarmLimitDb: java.lang.Double = _
但是我试图减少对 Java API 的依赖,那么我如何表示装箱的 < code>Double 没有它吗? ]
In Scala there are 2 representations of double-precision numbers, one is an AnyVal
, the other AnyRef
. On the JVM they are mapped to the primitive double
and the class java.lang.Double
respectively.
Now what happens on platforms other than the JVM? I can use Scala.Double
for the primitive, but how do I specify that I want a reference to the boxed Double without specifying java.lang.Double
?
[Context - left to make sense of Thomasz' answer, but not the fundamental issue.
I have a Double that I want to inject with Spring into a Wicket component:
class MyPanel(id: String) extends Panel(id) {
@SpringBean(name="rxAlarmLimitDb") var alarmLimitDb: Double = _
If I specify the type as scala.Double
as above, the injector fails, as it can only inject Objects.
If I specify java.lang.Double
as the type of the field, all is well
class MyPanel(id: String) extends Panel(id) {
@SpringBean(name="rxAlarmLimitDb") var alarmLimitDb: java.lang.Double = _
But I'm trying to reduce my dependance on falling back on the Java API, so how do I represent the boxed Double
without it?
]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Java 中的 scala.Double == double 。当您装箱
scala.Double
时,它会变成java.lang.Double
。没有任何方法可以创建
scala.Double
类型的对象。它只是 double 的别名。因此,对于您的问题,您需要使用 java.lang.Double,或者将其包含在您自己的类型中并提供隐式转换。如果你仔细想想,这个定义是有道理的。 java 和 java 之间的所有交互需要自动装箱的 scala 代码拆箱将按预期进行。
如果它有所作为,你总是可以这样做:
那么你就不必看到 java.lang :-)
scala.Double
==double
in Java. When you box ascala.Double
, it becomes ajava.lang.Double
.There isn't any way of creating an object of type
scala.Double
. It's just an alias for double. So for your problem, you need to use ajava.lang.Double
, or enclose it in your own type and provide implicit conversions.This definition makes sense if you think about it. All of the interaction between java & scala code which requires autoboxing & unboxing will work as expected.
If it makes a difference, you can always do:
then you won't have to see the java.lang :-)
为什么不创建 scala.Double 类型的 bean?很糟糕,但似乎有效:
Why not creating a bean of type
scala.Double
? Terrible but seems like it's working: