我想创建一个Any类型的数组,看起来像:
val arr: Array[Any] = Array(Array(1, 2, Array(3)), 4)
Run Code Online (Sandbox Code Playgroud)
然后我想使用此代码使用尾递归使其变平:
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
}
Run Code Online (Sandbox Code Playgroud)
我正在使用Scala 2.12版本.
当迭代Array(3)从源数组进入内部数组时,模式匹配case h: Array[Any]不起作用.这很奇怪,因为Int延伸Any.我试图调试并意识到这个数组是int[1](原始int数组).
为什么scala决定将它作为原始数组,以及如何弄清楚这种情况?