2012-07-05 43 views
1

我正在寻找一种方法来处理一个任何数组或序列,并在可能的情况下迭代它。Scala:如何处理任何像Array或Seq?

目前我有一些代码,看起来像这样,采取Any的序列,并展平包含任何Traversable或Array对象。

​​

感觉就像mustr是一个简单的方法在Scala中完成这项工作,给定了隐式转换和什么。任何人?

回答

2

基本上你想强制每个元素到Seq,然后将它们一次全部压扁。 Array具有隐式转换为Seq,并且SeqTraversable都具有.toSeq方法。因此,我们可以这样做:

val t: Traversable[Int] = List(1, 2, 3) 
val a: Array[Int] = Array(4, 5, 6) 
val other = "whatever" 
val as: Seq[Any] = List(t, a, other) 

as.flatMap{ 
    case t: Traversable[_] => t.toSeq 
    case a: Array[_] => a.toSeq 
    case other => Seq(other) 
}.map{_.toString} 
//Seq[java.lang.String] = List(1, 2, 3, 4, 5, 6, whatever) 

(顺便说一句,这是很丑陋的Scala代码,你可能要考虑重构事情摆脱首先使用Seq[Any]的)

+4

或者等价地: 'as.flatMap {...} .map(_。toString)'。 – 2012-07-05 17:58:44

+0

更清洁,谢谢。我真正想要的是一种将Traversable和Array案例合并为一个的方法。看起来像阵列到Seq的隐式转换应该允许你以某种方式做到这一点。 – 2012-07-05 18:37:58

+0

我同意Seq [Any]不理想。这一切都源于Play 2的WS框架,它将查询参数表示为Map [String,String]。随后我想支持多值参数,所以我的代码实际上有一个Map [String,Any]。 – 2012-07-05 19:10:15