Created
February 5, 2014 06:02
-
-
Save ryanlecompte/8818143 to your computer and use it in GitHub Desktop.
Option.collect, similar to Future.collect
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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