Search code examples
scalarecursioncasting

Print array with different deep


I have this function in Scala:

def printA(A: Array[_]): Unit = {
    if (A.isInstanceOf[Array[Int]]) A.foreach(t => println(t))
    else A.foreach(a => printA(a))
  }

I don't know, how to fix this error, that printA(a) is Any. The function accepts input Array[_]

Thanks, guys!


Solution

  • Maybe, it is better to check an element instead of an array?

      def printA(array: Array[_]): Unit = {
        array.foreach {
          case i: Int => println(i)
          case arr: Array[_] => printA(arr)
          case unknown => sys.error("Unsupported element: "+unknown) 
        }
      }