How to flatten a List of different types in Scala?

clau picture clau · Nov 15, 2009 · Viewed 22k times · Source

I have 4 elements:List[List[Object]] (Objects are different in each element) that I want to zip so that I can have a List[List[obj1],List[obj2],List[obj3],List[obj4]]

I tried to zip them and I obtained a nested list that I can't apply flatten to because it says: no implicit argument matching parameter type.

How can I solve this? should I try another way or is there any way to make the flatten work?

I'm kinda new to scala so it may be a dumb question :D Thanks in advance! clau

Answer

Jatin picture Jatin · Apr 16, 2013

For One Nested List: flatten will do:

scala> List(List(1), List(2), List(3)).flatten
res4: List[Int] = List(1, 2, 3)

scala> List(List(List(1)), List(List(2)), List(List(3))).flatten
res5: List[List[Int]] = List(List(1), List(2), List(3))

For multiple Nested Lists then you can:

def flatten(ls: List[Any]): List[Any] = ls flatMap {
  case i: List[_] => flatten(i)
  case e => List(e)
}

val k = List(1, List(2, 3), List(List(List(List(4)), List(5)), List(6, 7)), 8)
flatten(k)

It prints List[Any] = List(1, 2, 3, 4, 5, 6, 7, 8)