Search code examples
scalasequencescala-option

Appending list of optional elements


I need to make a sequence that, given a list containing optional list of strings, concatenates all of them to make a new list. This how my code looks like:

      res.foldLeft(Seq[Option[Seq[String]]]())((acc, v) => v match {
      case Some(x) => acc ++: Some(x)
      case None => acc
    })

where res is a list containing optional list elements such as :

List(Some(Seq(foo)), Some(Seq(bar)), None, Some(Seq(baz, blah)))

I get a compilation error at the sign ++: saying:

  type mismatch; found : Iterable[Equals] required: Seq[Option[Seq[String]]]

What am I doing wrong here?


Solution

  • Why don't you just do:

    res.flatten.flatten
    

    first flatten will get rid of Nones and expose the Options and second one will perform the expected flattening operation on the Seqs