Override Java methods that require double arrays
•
Java
Suppose I define the following Java interfaces:
public interface A { public Double[] x(); }
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 gave 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?
Xie Xie Mei
Solution
You cannot convert it automatically The problem is that double in Java means class java Lang. double (in Scala, it means that Scala. Double is roughly the same as double in Java), so the rewriting method must 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 can implicitly do this conversion:
implicit def wrapDoubleArray(arr: Array[Double]): Array[java.lang.Double] = arr.map(java.lang.Double.valueOf(_))
But in most cases this is a bad idea
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码