I’m looking for a way to treat an Any as an Array or Seq and iterate over it, if possible.
Currently I have some code that looks like this, taking a sequence of Any’s and flattening out any Traversable or Array objects contained.
def flattenAsStrings(as: Seq[Any]): Seq[String] = {
val (travValued, other) = as.partition(a => classOf[Traversable[_]] isAssignableFrom(a.getClass))
val (arrayValued, singleValued) = other.partition(a => a.isInstanceOf[Array[_]])
val travStrings = travValued.map(_.asInstanceOf[Traversable[_]].map(_.toString)).flatMap(_.toList)
val arrayStrings = arrayValued.map(_.asInstanceOf[Array[_]].map(_.toString)).flatMap(_.toList)
singleValued.map(_.toString) ++ travStrings ++ arrayStrings
}
It feels like there mustr be a simpler way to do this in Scala, given implicit conversions and whatnot. Anyone?
Basically you want to force each element to a
Seq, and then flatten them all at once.Arrayhas an implicit conversion toSeqand bothSeqandTraversablehave a.toSeqmethod. So we can do:(as an aside, this is pretty ugly Scala code, you might want to consider refactoring things to get rid of using a
Seq[Any]in the first place)