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
^
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?
The multiplication operator * and the “multiplyExact()” method can be used to multiply two values in java. The multiplication operator performs multiplication on any numeric value such as int, float, or double.
This is not possible.
def multiply(m: Int)(n: Int): Int = m * n.
When one operand is an int and the other is a double, Java creates a new temporary value that is the double version of the int operand. For example, suppose that we are adding dd + ii where ii is an int variable. Suppose the value of ii is 3. Java creates a temporary value 3.0 that is the corresponding double value.
I would define an implicit conversion to a Scala Double
implicit def javaToScalaDouble(d: java.lang.Double) = d.doubleValue
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)
-- Flaviu Cipcigan
For the "native" Doubles there is no problem (tried this in scala interpreter 2.7.5):
scala> val a = 34D
a: Double = 34.0
scala> val b=54D
b: Double = 54.0
scala> val c = a+b
c: Double = 88.0
scala> val c=a*b
c: Double = 1836.0
The way java.lang.Double is represented, seems to be a bit strange though...
scala> val t:java.lang.Double = new java.lang.Double(4)
t: java.lang.Double = 4.0
scala> val s:java.lang.Double = new java.lang.Double(4)
s: java.lang.Double = 4.0
scala> val i = s+t
<console>:6: error: type mismatch;
found : java.lang.Double
required: String
val i = s+t
^
scala> val i = s.doubleValue+t.doubleValue
i: Double = 8.0
Looks like conversion to "native" Doubles is the best approach...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With