2
votes

I want to create array of Any type, which looks like:

val arr: Array[Any] = Array(Array(1, 2, Array(3)), 4)

Then I want to make it flatten using tail recursion with this code:

def flatten(xs: Array[Any]): Array[Any] = {

    @tailrec
    def makeFlat(xs: List[Any], res: List[Any]): List[Any] = xs match {
      case Nil => res
      case head :: tail => head match {
        case h: Array[Any] => makeFlat(h.toList ::: tail, res)
        case _ => makeFlat(tail, res :+ head)
      }
    }

    makeFlat(xs.toList, Nil).toArray
}  

I'm using Scala 2.12 version.

When iteration comes to internal array Array(3) from source array, pattern matching case h: Array[Any] is not working. This is strange, because Int extends Any. I've tried to debug and realized that this array is int[1] (array of primitive int).

Why scala decided to make it as primitive array and how I can figure out this case?

2
Scala infers the type of the Array(3) as Array[Int], since you are only storing an Int in it. Your type of Array[Any] only refers to the top-level array. val arr: Array[Any] = Array(Array(1, 2, Array[Any](3)), 4) will create an Array[Any] for Array(3). - sheunis

2 Answers

5
votes

It's not working because you're not letting it infer the type.

Replace case h: Array[Any] with case h: Array[_] and you're golden.

0
votes

Array is a java class, not scala class

It doesn't support variances

See http://docs.scala-lang.org/tutorials/tour/variances.html