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
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.
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(_) }
}
}
Will this help?
class B extends A {
val v: Array[java.lang.Double] = Array(2.3D, 6.7D)
override def x() = v
}
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