Scala通过多种类型解复用Array

时间:2014-11-21 11:24:05

标签: scala dynamic types scala-collections

val a: Array[Any] = Array(1,"a",2,3.12,"c")

如何获得

val out = Array[Array[Any]] = Array(Array(1,2), Array(3.12), Array("a","c"))

1 个答案:

答案 0 :(得分:4)

val aInt = a.collect { case i: Int => i } 
val aDouble = a.collect { case d: Double => d }
val aString = a.collect { case s: String => s }

或更一般地

def filterByType[A: scala.reflect.ClassTag](a: Array[Any]) =
  a.collect { case x: A => x }

关于上次更新,您可以按运行时类进行分组并获取值:

a.groupBy(_.getClass).values.toArray