2
我有一个类型为Seq[Array[Int]]
的值,我想最后只有一个Array[Int]
。我以为foldLeft会的工作,但意外的是没有:如何在scala中合并一个数组序列
scala> val arr1 = Array(1,2,3)
arr1: Array[Int] = Array(1, 2, 3)
scala> val arr2 = Array(4,5,6)
arr2: Array[Int] = Array(4, 5, 6)
scala> val seq = Seq(arr1, arr1)
seq: Seq[Array[Int]] = List(Array(1, 2, 3), Array(1, 2, 3))
scala> seq.foldLeft (Array.empty)((x,y) => x ++ y)
<console>:17: error: value ++ is not a member of Array[Nothing]
seq.foldLeft (Array.empty)((x,y) => x ++ y)
^
似乎错误并不像整个真相,但因为我可以这样做:
scala> Array.empty
res22: Array[Nothing] = Array()
scala> Array.empty ++ arr1 ++ arr2
res23: Array[Int] = Array(1, 2, 3, 4, 5, 6)
是怎么回事?
感谢您的解释。我仍然熟悉scala的类型推断。但你说得对,'seq.flatten.toArray'更好。 – doub1ejack