在Scala中键入与Array数组不匹配(Type mismatch with Array of Array in Scala)

编程入门 行业动态 更新时间:2024-10-26 21:33:32
在Scala中键入与Array数组不匹配(Type mismatch with Array of Array in Scala)

我正在尝试构建一个数组数组,以将其作为方法的参数。 内部数组的值是任何类型的数据(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) # <-- ERROR2

However, 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.

更多推荐

本文发布于:2023-08-03 00:23:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1382448.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   不匹配   Array   Scala   Type

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!