tags:

views:

563

answers:

3

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?

+7  A: 

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

Flaviu Cipcigan
A: 

I suspect you are entering x*y instead of x * y The spaces are important, as the scala parser allows for non-alphanumeric characters in identifiers.

Brian
This answer is quite wrong. Non-alphanumeric characters *are* allowed, but they don't cause problems like this. The expression `x*y` is parsed as `x.*(y)` (exactly the same as `x * y`) precisely because mixed alpha/non-alphanumeric characters must be delimited in identifiers using underscores. Thus, `x*` is *not* a valid identifier, but `x_*` is.
Daniel Spiewak
+1  A: 

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

Ashalynd