Search code examples
arraysscalafoldleft

How to merge a sequence of arrays in scala


I have a value of type Seq[Array[Int]] and I want to end up with a single Array[Int]. I thought foldLeft would work, but surprisingly it doesn't:

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 )
                                                ^

That error doesn't seem like the entire truth though because I can do this:

scala> Array.empty
res22: Array[Nothing] = Array()

scala> Array.empty ++ arr1 ++ arr2
res23: Array[Int] = Array(1, 2, 3, 4, 5, 6)

What gives?


Solution

  • What about seq.flatten.toArray ?

    For foldLeft solution you should tell type to compiler: Array.empty[Int], when you missed that [Int], the compiler chose Nothing as the only possible type for Array.empty.