当某些元素不是数组时,在 Scala 2.8 中展平数组
如果我有
var a = Array(Array(1, 2), 3, Array(4,5,6))
并且我想将其转换为
Array(1, 2, 3, 4, 5, 6)
最简单的方法是什么?
我也尝试过
def flatArray(a:Array[Any])= a.map(x => x match { case ar:Array[_] => ar; case _ => Array(x) } )
,但输出是 ArraySeq 类型,我无法看到如何将其转换为 Array
If I have
var a = Array(Array(1, 2), 3, Array(4,5,6))
and I want to convert this to
Array(1, 2, 3, 4, 5, 6)
what is the easiest way to do it? There is a solution for lists given in this post
but it does not work for arrays.
I also tried
def flatArray(a:Array[Any])= a.map(x => x match { case ar:Array[_] => ar; case _ => Array(x) } )
but the output is of type ArraySeq
and I am not able to see how to convert it to Array
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我也尝试过使用 #flatten 方法,但它在 NPE 上失败。
更新:回答 Jus12 的问题:
当然整个解决方案不是类型安全的。原因是为了适应编译器的类型推断,将
Array(Array(1, 2), 3, Array(4,5,6))
推断为Array[Any]
。准确的类型是“Int
或Array[Int]
的数组”,但这是不可能的。就是创建一个 Either 元素数组,其中每个元素都是Either[Int, Array[Int]]
并使用它:请参阅:
注意:EitherView 的原始想法是由@Mitch Blevins 提出的: http://cleverlytitled.blogspot.com/2009/03/disjoint -bounded-views-redux.html
I've tried also to use the #flatten method, but it fails on NPE.
Update: To answer Jus12's question:
Of course the whole solution is not type safe. The reason is to accommodate the compiler's type inference which infers
Array(Array(1, 2), 3, Array(4,5,6))
asArray[Any]
. An accurate type is "an array of eitherInt
orArray[Int]
", but that is not possible. What is is to create an array of Either elements where each element isEither[Int, Array[Int]]
and work with that:See:
Note: The original idea for EitherView is by @Mitch Blevins: http://cleverlytitled.blogspot.com/2009/03/disjoint-bounded-views-redux.html
与 IttayD 类似,没有 ClassManifest,并具有 Array[Any] 作为结果。
Similar to IttayD, without ClassManifest, and has Array[Any] as result.