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?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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
well, calling toArray[Any] at the very end is always an option
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.
I guess w/o specialization you box anyway. Which I guess is obvious.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.