Suppose I have a List of things on which I want to do something that may fail. In this example I have a List of Strings that I want to turn into a List of Integers.

val strings = List("1", "bla", "4")

The problem is that some of the strings can't be parsed. And I don't know which, until I try to parse them. So it's impossible to filter them out beforehand. flatMap comes to the rescue!

val integers = strings.flatMap { s =>
  try {
    List(Integer.parseInt(s))
  } catch {
    case _: NumberFormatException => Nil
  }
}

Because we're flatMapping over a List, it's normal to return a List. If we look at the documentation we can return a lot more.

final def flatMap[B](f: (A) ⇒ GenTraversableOnce[B]): List[B]

So we can write the code in a clearer way with Option.

val integers = strings.flatMap { s =>
  try {
    Some(Integer.parseInt(s))
  } catch {
    case _: NumberFormatException => None
  }
}
shadow-left