Scala Saturday – The flatten Method


All of Scala’s collections define a flatten method that takes a collection of collections and flattens them. That is, it takes the elements of the nested collections, pulls them out, and puts them all together in a new collection. For sequential collections, such as a list, the new collection maintains the order of the elements in the original collections.

To illustrate, let’s say that the heroes of Icewind Dale have to team up with their roguish nemeses to fight a common enemy:

val heroes = List("Drizzt", "Bruenor", "Wulfgar", "Catti-brie")
val rogues = List("Jarlaxle", "Artemis")
val teams = List(heroes, rogues)
// teams: List[List[String]] =
//   List(
//     List(Drizzt, Bruenor, Wulfgar, Catti-brie),
//     List(Jarlaxle, Artemis) )

So now you have a list of lists. To get your temporary alliance, you call flatten on podcasts:

val alliance = teams.flatten
// alliance: List[String] =
//   List(Drizzt, Bruenor, Wulfgar, Catti-brie, Jarlaxle, Artemis)

As you can see, flatten flattens the nested lists into one long list and preserves the order of the elements as they were in the original nested lists.


Hey, strings are collections, too, right? Collections of characters, so if it should ever suit your needs, you can flatten a collection of strings into a collection of characters:

val atrocious = List(
  "super", "cali", "fragi", "listic", "expi", "ali", "docious")
val precocious = atrocious.flatten
// precocious: List[Char] = List(s, u, p, e, r, c, a, l, i, ...

Of course, more times than not, you probably want to combine those strings into one long string rather than a sequence of characters. That’s where mkString comes in. It concatenates a collection of strings together, delimited by whatever separator you prescribe. (Some languages call this operation “join.”) Like so:

val delimited = List("lock", "stock", "barrel") mkString ", "
// delimited: String = lock, stock, barrel

And if you just want to jam the strings all together with no delimiter, just use an empty string as the delimiter:

val precocious = atrocious mkString ""
// precocious: String = supercalifragilisticexpialidocious

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.