30

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.

Xavier Guihot
  • 54,987
  • 21
  • 291
  • 190
ssanj
  • 2,169
  • 3
  • 19
  • 28
  • 1
    `filter` + `map` can be reduced to `collect` which takes partial function as a parameter. – tiran Nov 19 '13 at 08:06

1 Answers1

53

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
  • 26,420
  • 4
  • 61
  • 81
  • 3
    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 Aug 26 '10 at 05:25
  • 12
    Not so surprising, because `flatMap(fun)` == `map(fun).flatten`. – Debilski Aug 26 '10 at 16:29
  • 4
    What do you mean by "Absolutely, positively not. (Not!)" Doesn't your code demo this working? – Richard Tingle Mar 02 '17 at 16:15