如果我有
var a = Array(Array(1, 2), 3, Array(4,5,6))
我希望将其转换为
Array(1, 2, 3, 4, 5, 6)
最简单的方法是什么? this post中给出的列表解决方案 但它不适用于数组。
我也试过
def flatArray(a:Array[Any])= a.map(x => x match { case ar:Array[_] => ar; case _ => Array(x) } )
但输出属于ArraySeq
类型,我无法看到如何将其转换为Array
答案 0 :(得分:8)
def flatArray[T : ClassManifest](a:Array[Any]) =
a.flatMap{
case ar:Array[T] => ar
case x: T => Array(x)
}
我也试过使用#flatten方法,但它在NPE上失败了。
更新:回答Jus12的问题:
def flatArray[T : Manifest](a:Array[Any]) =
a.flatMap{
case ar: Array[_] if ar.getClass.getComponentType == manifest[T].erasure => ar.asInstanceOf[Array[T]];
case x => Array(x.asInstanceOf[T])
}
当然整个解决方案并不是类型安全的。原因是适应编译器的类型推断,推断Array(Array(1, 2), 3, Array(4,5,6))
为Array[Any]
。准确的类型是“Int
或Array[Int]
”的数组,但这是不可能的。什么是创建一个Either元素数组,其中每个元素都是Either[Int, Array[Int]]
并使用它:
object EitherView {
type ||[A, B] = Either[A, B]
// convenience of definition functions
private def l[A,B](a: A): ||[A,B] = Left(a)
private def r[A,B](b: B): ||[A,B] = Right(b)
// implicit defs - stuttering-or
implicit def aToOr2[A,B](a: A): A || B = l(a)
implicit def bToOr2[A,B](b: B): A || B = r(b)
implicit def aToOr3[A,B,C](a: A): A || B || C = l(l(a))
implicit def bToOr3[A,B,C](b: B): A || B || C = l(r(b))
implicit def aToOr4[A,B,C,D](a: A): A || B || C || D = l(l(l(a)))
implicit def bToOr4[A,B,C,D](b: B): A || B || C || D = l(l(r(b)))
implicit def aToOr5[A,B,C,D,E](a: A): A || B || C || D || E = l(l(l(l(a))))
implicit def bToOr5[A,B,C,D,E](b: B): A || B || C || D || E = l(l(l(r(b))))
// more? ...
}
import EitherView._
type CompoundArray[T] = Array[T || Array[T]]
object CompoundArray {
def apply[T](elems: (T || Array[T])*) = elems.toArray
}
def flatArray[T : Manifest](a:CompoundArray[T]) = {
a.flatMap{
case Left(x) => Array(x)
case Right(x) => x
}
}
请参阅:
scala> val a = CompoundArray[Int](Array(1, 2), 3, Array(4,5,6))
a: Array[EitherView.||[Int,Array[Int]]] = Array(Right([I@1364b53), Left(3), Right([I@18b62e0))
scala> flatArray(a)
res0: Array[Int] = Array(1, 2, 3, 4, 5, 6)
scala> flatArray(CompoundArray[String](Array("hi"), "bye"))
res4: Array[String] = Array(hi, bye)
scala> flatArray(CompoundArray[String](Array("hi"), 3))
<console>:13: error: type mismatch;
found : Int(3)
required: EitherView.||[String,Array[String]]
flatArray(CompoundArray[String](Array("hi"), 3))
^
注意:EitherView的最初想法是@Mitch Blevins:http://cleverlytitled.blogspot.com/2009/03/disjoint-bounded-views-redux.html
答案 1 :(得分:3)
类似于IttayD,没有ClassManifest,并且结果为[Any]。
scala> a.flatMap{
| case ar: Array[_] => ar
| case x => List(x)
| }
res4: Array[Any] = Array(1, 2, 3, 4, 5, 6)