Override java method that expects double array

Let's 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

+6
source share
3 answers

You cannot convert it automatically. The problem is that Double in Java means the class java.lang.Double (while in Scala it means scala.Double , which basically matches Double in Java), and therefore the overriding method should return Array[java.lang.Double] , If you have 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 can 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 cases.

+6
source

If type v should be Array[scala.Double] , perhaps you should consider converting yourself in an 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(_) } } } 
+2
source

Did it help?

 class B extends A { val v: Array[java.lang.Double] = Array(2.3D, 6.7D) override def x() = v } 
+1
source

All Articles