Scala nested arrays flattening

不羁的心 提交于 2019-12-05 13:52:05

If you have mixed Int and Array[Int], which is not a very good idea to begin with, you can do something like

in.flatMap{ case i: Int => Array(i); case ai: Array[Int] => ai }

(it will throw an exception if you've put something else in your array). You can thus use this as the basis of a recursive function:

def flatInt(in: Array[Any]): Array[Int] = in.flatMap{
  case i: Int => Array(i)
  case ai: Array[Int] => ai
  case x: Array[_] => flatInt(x.toArray[Any])
}

If you don't know what you've got in your nested arrays, you can replace the above Ints by Any and get a flat Array[Any] as a result. (Edit: the Any case then needs to go last.)

(Note: this is not tail-recursive, so it can overflow the stack if your arrays are nested extremely deeply.)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!