Search code examples
scalacollectionsoption-type

Scala: What's the best way to filter and flatten Seq[Option[A]]


Let's say I have a val allStrs: Seq[Option[String]] = Seq(Some("A"), Some("B"), None)

And would like to have a result like this: Seq("A", "B"), what's the most elegant/Scala way to do this?

I have one way is allStrs.filter(_.isDefined).flatten, is it the best way?


Solution

  • As mentioned in the comments, this will work:

    val allStrs: Seq[Option[String]] = ???
    val s: Seq[String] = allStrs.flatten 
    

    The flatten operation operates on a sequence of containers. It takes the elements out of each of the individual containers and creates a single sequence containing all those elements.

    Option behaves a lot like like a container with 0 or 1 elements. So flatten on a sequence of Options will extract the values from those Options. It removes all None values in the sequence and extracts the contents of all the Some values.