Scala 不能乘以 Java Doubles? [英] Scala can't multiply java Doubles?
问题描述
在 Scala 中使用 Java 类时,我注意到 Scala 不能乘以 Java Doubles.举个例子:
While working with a Java class in Scala, I noticed that Scala can't multiply Java Doubles. Here's an example:
scala> val x:java.lang.Double = new java.lang.Double(34.0)
x: java.lang.Double = 34.0
scala> val y:java.lang.Double = new java.lang.Double(2.1)
y: java.lang.Double = 2.1
scala> x*y
<console>:7: error: value * is not a member of java.lang.Double
x*y
^
哇!我猜这是因为 Scala 运算符只是方法,所以它试图调用 Java Double 类的乘法方法(即34.0.*(2.1)").哎呀.有没有一种简单的方法来执行此互操作?
Whoa! I guess it's because Scala operators are just methods, so it's trying to call the multiply method of the Java Double class (ie, "34.0.*(2.1)"). Oops. Is there an easy way to do this interop?
推荐答案
我会定义一个到 Scala 的隐式转换 Double
I would define an implicit conversion to a Scala Double
implicit def javaToScalaDouble(d: java.lang.Double) = d.doubleValue
现在您的代码可以运行了!类似的表达式如 1.2 + x
也可以使用.并且由于自动装箱代码,如下所示确实不需要隐式转换即可编译.
Now your code works! And similarly expressions like 1.2 + x
work as well. And due to auto-boxing code like the following does compile without requiring implicit conversions.
def foo(d: java.lang.Double) = println(d)
val z: scala.Double = 1.2
foo(z)
--弗拉维乌·西皮根
这篇关于Scala 不能乘以 Java Doubles?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!