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

前端 未结 6 2146
长发绾君心
长发绾君心 2020-12-05 22:43

What\'s the best way to convert a List of Lists in scala (2.9)?

I have a list:

List[List[A]]

which I want to convert into

6条回答
  •  心在旅途
    2020-12-05 23:14

    You don't need recursion but you can use it if you want:

    def flatten[A](list: List[List[A]]):List[A] = 
      if (list.length==0) List[A]() 
      else list.head ++ flatten(list.tail)
    

    This works like flatten method build into List. Example:

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

提交回复
热议问题