Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala can't multiply java Doubles?

Tags:

scala

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?

like image 359
DrGary Avatar asked Oct 09 '09 18:10

DrGary


People also ask

How do you multiply double in Java?

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.

Can you multiply a double by an int Java?

This is not possible.

How do you do multiplication in Scala?

def multiply(m: Int)(n: Int): Int = m * n.

What happens when you multiply an int by a double in Java?

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.


2 Answers

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

like image 139
Flaviu Cipcigan Avatar answered Dec 28 '22 22:12

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...

like image 45
Ashalynd Avatar answered Dec 28 '22 20:12

Ashalynd