Consider the code:
val arr2d = Array(Array(1, 2, 3), Array(4, 5, 6))
util.Arrays.deepToString(arr2d)
It fails with the following error on the second line:
Error:(79, 30) type mismatch;
found : Array[Array[Int]]
required: Array[Object] Note: Array[Int] <: Object, but class Array is invariant in type T. You may wish to investigate a wildcard type such as_ <: Object
. (SLS 3.2.10) util.Arrays.deepToString(arr2d)
It has problaby something with type erasure, but I am not exactly sure what to do to make the code compile, despite the compiler trying to suggest a solution. I am even more puzzled because the analogous Java code works (i.e. something along the lines of Arrays.deepToString(new int[][] { { 1, 2, 3}, {4, 5, 6}})
).
What is the problem in the code and how can it fixed?
java.util.Arrays.deepToString(arr2d.asInstanceOf[Array[Object]])
The original code does not work, because in ScalaArrays
are invariant instead of covariant (which they are in Java). BTW, Since you only need theString
, have you consider this alternative:arr2d.map(_.mkString("[", ", ", "]")).mkString("[", ", ", "]")
? – Luis Miguel Mejía SuárezdeepToString
- for example, wouldn't work with arrays nested 3 times (i.e.Array(Array(Array(1)))
). – lukeg