eg04lt3r
eg04lt3r

Reputation: 2610

Pattern matching on nested arrays in Scala

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?

Upvotes: 2

Views: 779

Answers (2)

Zang MingJie
Zang MingJie

Reputation: 5285

Array is a java class, not scala class

It doesn't support variances

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

Upvotes: 0

airudah
airudah

Reputation: 1179

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.

Upvotes: 5

Related Questions