我正在尝试构建一个数组数组,以将其作为方法的参数。 内部数组的值是任何类型的数据(AnyVal),例如Int或Double。
该方法的签名如下:
def plot[T <: AnyVal](config:Map[String, String], data:Array[Array[T]]): Unit = {这是代码:
val array1 = (1 to 10).toArray val array2 = ArrayBuffer[Int]() array1.foreach { i => array2 += (getSize(summary, i)) } val array3 = new Array[Int](summary.getSize()) val arrays = ArrayBuffer[Array[AnyVal]](array1, array2.toArray, array3) # <-- ERROR1 Gnuplotter.plot(smap, arrays.toArray) # <-- ERROR2但是,我有两个错误:
什么可能是错的?
I'm trying to build an array of an array to give it as a argument to a method. The value of inner arrays are any kind of data (AnyVal) such as Int or Double.
The method's signature is as follows:
def plot[T <: AnyVal](config:Map[String, String], data:Array[Array[T]]): Unit = {This is the code:
val array1 = (1 to 10).toArray val array2 = ArrayBuffer[Int]() array1.foreach { i => array2 += (getSize(summary, i)) } val array3 = new Array[Int](summary.getSize()) val arrays = ArrayBuffer[Array[AnyVal]](array1, array2.toArray, array3) # <-- ERROR1 Gnuplotter.plot(smap, arrays.toArray) # <-- ERROR2However, I have two errors:
What might be wrong?
最满意答案
Array是一个可变数据结构,不是协变的( 这就是为什么 )
因此, Array[Int]不是Array[AnyVal]的子类型,因此您无法在需要Array[AnyVal]位置传递它。
List会为您做什么吗?
如果性能很重要并且你真的需要使用Array ,你可以简单地将所有内容都转换为Array[Any]并完成它。
或者,如果您只需要一个Array[Any]作为传递给plot函数的最终类型,您可以使用List执行所有操作,并在最后使用toArray[Any]进行转换。
Array, being a mutable data structure, is not covariant (here's why)
So Array[Int] is not a subtype of Array[AnyVal], hence you cannot pass it where an Array[AnyVal] is expected.
Would a List do for you purposes?
In case performance matters and you really need to use Array, you can simply cast everything to an Array[Any] and be done with it.
Alternatively, if you just need an Array[Any] as the final type to pass to the plot function, you can do everything with List, and convert it with toArray[Any] at the very end.
更多推荐
发布评论