Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override a java method that expects a double array

Tags:

java

scala

Say I define the following java interface:

public interface A
{
  public Double[] x();
}

And then try to implement it in scala as follows:

class B extends A {
  val v: Array[Double] = Array(2.3, 6.7)
  override def x() = v
}

The compiler gives me the following error:

type mismatch;
[error]  found   : Array[scala.Double]
[error]  required: Array[java.lang.Double]
[error]     override def x() = v

Can someone tell me the recommended way to automatically convert this array?

Thanks Des

like image 844
user79074 Avatar asked Apr 01 '14 16:04

user79074


3 Answers

You can't convert it automatically. The issue is that Double in Java means the class java.lang.Double (while in Scala it means scala.Double which is mostly the same as double in Java), and so the overriding method has to return Array[java.lang.Double]. If you have an Array[Double], you can convert it using map:

val v: Array[Double] = ...
val v1 = v.map(java.lang.Double.valueOf(_)) // valueOf converts Double into java.lang.Double

You could make this conversion implicit:

implicit def wrapDoubleArray(arr: Array[Double]): Array[java.lang.Double] =
  arr.map(java.lang.Double.valueOf(_))

but this is a bad idea in most circumstances.

like image 103
Alexey Romanov Avatar answered Oct 23 '22 14:10

Alexey Romanov


If the type of v must be Array[scala.Double], then perhaps you should consider performing the conversion yourself in the overridden method:

class B extends A {
  val v: Array[Double] = Array(2.3, 6.7)

  override def x(): Array[java.lang.Double] = {
    v map { java.lang.Double.valueOf(_) }
  }
}
like image 2
Daniel Miladinov Avatar answered Oct 23 '22 14:10

Daniel Miladinov


Will this help?

class B extends A {
  val v: Array[java.lang.Double] = Array(2.3D, 6.7D)
  override def x() = v
}
like image 1
WeMakeSoftware Avatar answered Oct 23 '22 14:10

WeMakeSoftware