1

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:

enter image description here enter image description here

What might be wrong?

prosseek
  • 182,215
  • 215
  • 566
  • 871

1 Answers1

6

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.

Community
  • 1
  • 1
Gabriele Petronella
  • 106,943
  • 21
  • 217
  • 235
  • s/Int/AnyVal you mean? Of course, upcasting is a solution, kind of a ugly one though. Unless performance is crucial I would just avoid using mutable data structures – Gabriele Petronella Aug 21 '14 at 18:50
  • well, calling `toArray[Any]` at the very end is always an option – Gabriele Petronella Aug 21 '14 at 21:21
  • as always, it's a tradeoff. Unless performance is not an critical issue (in which case you would care about integer boxing), I very much prefer working with an immutable collection, rather than casting everything to `Any`. In the OP example, `Int` boxing isn't going to make any significant difference. – Gabriele Petronella Aug 21 '14 at 21:38
  • I guess w/o specialization you box anyway. Which I guess is obvious. – som-snytt Aug 22 '14 at 00:16