2

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?

doub1ejack
  • 10,627
  • 20
  • 66
  • 125

1 Answers1

8

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.

Nathaniel Ford
  • 20,545
  • 20
  • 91
  • 102
dveim
  • 3,381
  • 2
  • 21
  • 31
  • Thanks for the explanation. I'm still getting familiar with scala's type inference. But you're right, `seq.flatten.toArray` is nicer. – doub1ejack Aug 26 '16 at 14:26