All Articles



Concatenating two lists in Scala is relatively straight-forward.

  val a = List(1, 2, 3)
  val b = List(4, 5, 6)

  val c = a ++ b

  println(c)  // List(1,2,3,4,5,6)

Suppose instead that we have a list of lists and we wish to concatenate all of them into a single list.


Recall the foldLeft method (a blackbox for tail-recursion).

Recall that foldLeft can be used to perform aggregate type of operations on a list. For example, to compute the sum of the elements of a list.

  def sum(list: List[Int]): Int = list.foldLeft(0)((sum,x) => sum + x)
  println(sum(List(1,2,3,4))) // 10

(sum is the accumulation at the given iteration, and x is the current element)

We can repeat this pattern to concatenate a list of lists.

  def flat(lol: List[List[Int]]): List[Int] = lol.foldLeft(List[Int]())((flat,x)=> flat ++ x)
  println(flat(List(List(1,2),List(3,4),List(5,6))))  // List(1,2,3,4,5,6)

There is a core Scala method that blackboxes this as well called, unsurprisingly, flatten.


  val lol = List(List(1, 2), List(3, 4), List(5, 6))
  val flat = lol.flatten
  println(flat) //  List(1,2,3,4,5,6)
Published 29 Jun 2018