Scala - convert List of Lists into a single List: List[List[A]] to List[A]

List has the flatten method. Why not use it?

List(List(1,2), List(3,4)).flatten
> List(1,2,3,4)

.flatten is obviously the easiest way, but for completeness you should also know about flatMap

 val l = List(List(1, 2), List(3, 4))
 println(l.flatMap(identity))

and the for-comprehension equivalent

 println(for (list <- l; x <- list) yield x)

flatten is obviously a special case of flatMap, which can do so much more.


Given the above example, I'm not sure you need recursion. Looks like you want List.flatten instead.

e.g.

scala> List(1,2,3)
res0: List[Int] = List(1, 2, 3)

scala> List(4,5,6)
res1: List[Int] = List(4, 5, 6)

scala> List(res0,res1)
res2: List[List[Int]] = List(List(1, 2, 3), List(4, 5, 6)) 

scala> res2.flatten
res3: List[Int] = List(1, 2, 3, 4, 5, 6)