Is there a simple way in Scala to flatten or "unlist" a nested sequence of sequences of sequences (etc.) of something into just a simple sequence of those things, without any nesting structure?
I don't think there is a flatten` method which converts a deeply nested into a sequence.
Its easy to write a simple recursive function to do this
def flatten(ls: List[Any]): List[Any] = ls flatMap {
case ms: List[_] => flatten(ms)
case e => List(e)
}
val a = List(List(List(1, 2, 3, 4, 5)),List(List(1, 2, 3, 4, 5)))
flatten(a)
//> res0: List[Any] = List(1, 2, 3, 4, 5, 1, 2, 3, 4, 5)
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