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

ssanj picture ssanj · Aug 26, 2010 · Viewed 8.8k times · Source

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.

Answer

Randall Schulz picture Randall Schulz · Aug 26, 2010

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)