I have a nested array:
Array("AA", Array("BB", "CC"), "DD"). How can I convert it into:
Array("AA", "BB", "CC", "DD") in Scala?
Thanks for help!
First of all check out the inferred type of the array:
scala> val arr = Array("AA", Array("BB", "CC"), "DD")
arr: Array[java.io.Serializable] = Array(AA, Array(BB, CC), DD)
Scala's collections have a single type for their elements, so if you put both a string and an array of strings (or an array of an array of strings) in an array, you'll end up with an array with an element type that's the most specific type shared by both String and Array[String]—in this case Serializable, which is pretty useless, since to do anything with the elements of the array you'll have to cast them to some other type.
So it's best not to get yourself into this situation in the first place. You'll get much more mileage out of the type system if you don't mix unrelated things in collections. That said, if you absolutely have to do this, you can write something like the following:
def flattenStringArrays[A](arr: Array[A]): Array[String] =
arr.flatMap {
case s: String => Array(s)
case a: Array[_] => flattenStringArrays(a)
}
And then:
scala> flattenStringArrays(arr)
res0: Array[String] = Array(AA, BB, CC, DD)
Or if you "know" you'll only ever have one level of nesting:
scala> arr.flatMap {
| case s: String => Array(s)
| case a: Array[String] => a
| }
res1: Array[String] = Array(AA, BB, CC, DD)
But both of these are unsafe and really unidiomatic.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With