2

我有一个 type 的值,Seq[Array[Int]]我想以一个Array[Int]. 我认为 foldLeft 会起作用,但令人惊讶的是它没有:

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)

是什么赋予了?

4

1 回答 1

8

怎么样seq.flatten.toArray

对于foldLeft解决方案,您应该告诉编译器类型:Array.empty[Int],当您错过时[Int],编译器选择Nothing作为唯一可能的类型Array.empty

于 2016-08-26T14:17:43.323 回答