Skip to content

Instantly share code, notes, and snippets.

@ryanlecompte
Created February 5, 2014 06:02
Show Gist options
  • Save ryanlecompte/8818143 to your computer and use it in GitHub Desktop.
Save ryanlecompte/8818143 to your computer and use it in GitHub Desktop.
Option.collect, similar to Future.collect
implicit class RichOption(underlying: Option.type) {
def collect[A](opts: Seq[Option[A]]): Option[Seq[A]] = {
@tailrec def rec(left: Seq[Option[A]], acc: Seq[A]): Option[Seq[A]] = {
left match {
case Seq(Some(v), tail @ _*) => rec(tail, acc :+ v)
case Seq(None, _*) => None
case _ => Option(acc)
}
}
rec(opts, Vector.empty)
}
}
scala> Option.collect(Seq(Some(1), Some(2), Some(3)))
res13: Option[Seq[Int]] = Some(Vector(1, 2, 3))
scala> Option.collect(Seq(Some(1), Option.empty[Int], Some(3)))
res14: Option[Seq[Int]] = None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment