Search code examples
scalascala-option

Does Scala have an API method that converts a Seq[Option[T]] to Seq[T]?


Is there a Scala API method to convert a Seq[Option[T]] -> Seq[T]?

You can do this manually via:

seq.filter(_.isDefined).map(_.get)

Wondering if there is a method that does the above in the general API.


Solution

  • Absolutely, positively not. (Not!)

    scala> val so1 = List(Some(1), None, Some(2), None, Some(3))
    so1: List[Option[Int]] = List(Some(1), None, Some(2), None, Some(3))
    
    scala> so1.flatten
    res0: List[Int] = List(1, 2, 3)