tags:

views:

109

answers:

1

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.

+12  A: 

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)
Randall Schulz
not? (15 chars)
abhin4v
Surprisingly so1.flapMap(r => r) also works. This seems to be due to the fact that Option can be converted to an iterable through: implicit def option2Iterable[A](xo: Option[A]): Iterable[A] = xo.toList. When xo.toList is called only Some(X) generate a list value. None gives a List(). Flatmap does the rest.
ssanj
Not so surprising, because `flatMap(fun)` == `map(fun).flatten`.
Debilski