0
votes

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?

1
This seem to work: java.util.Arrays.deepToString(arr2d.asInstanceOf[Array[Object]]) The original code does not work, because in Scala Arrays are invariant instead of covariant (which they are in Java). BTW, Since you only need the String, have you consider this alternative: arr2d.map(_.mkString("[", ", ", "]")).mkString("[", ", ", "]")?Luis Miguel Mejía Suárez
@LuisMiguelMejíaSuárez It works. Can you add an answer so that I can accept? Also, your alternative looks nice, but is not as universal as deepToString - for example, wouldn't work with arrays nested 3 times (i.e. Array(Array(Array(1)))).lukeg
You may write a Macro that using the static type of its input, generates the recursive call.Luis Miguel Mejía Suárez

1 Answers

0
votes

You can write your own deepToString with pattern matching and recursion:

def deepToString(array: Array[_]): String = array.map {
  case arr: Array[_] => deepToString(arr)
  case x => x.toString
}.mkString("[", ", ", "]")

val arr2d = Array(Array(1, 2, 3), Array(4, 5, 6))
val arr3d = Array(Array(Array(1,2,3), Array(4, 5, 6)), Array(Array(1,2,3), Array(4, 5, 6)))

deepToString(arr2d) // [[1, 2, 3], [4, 5, 6]]
deepToString(arr3d) // [[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]]

This should work for n-dimensional arrays as long as n is not big enough to cause stack overflow.