Skip to content

Instantly share code, notes, and snippets.

@dirkgr
Created December 1, 2015 02:20
Show Gist options
  • Save dirkgr/b3870a55fdc9309b255e to your computer and use it in GitHub Desktop.
Save dirkgr/b3870a55fdc9309b255e to your computer and use it in GitHub Desktop.
Function that returns the first failure or the first success out of an iterator of Try, without exhausting the iterator
/** Returns the first failure or the first success out of an iterator of Try, taking care not to
* exhaust the iterator when possible.
*
* @param tries The iterator of Try. Must not be empty.
* @param defaultFailure The return value to use if all tries left in the iterators are
* failures. If this is None, use the first failure from the iterator.
* @return the first success out of the iterator, or the first failure if there is no success
*/
@tailrec
def firstSuccessOrFirstFailure[A](
tries: Iterator[Try[A]],
defaultFailure: Option[Failure[A]] = None
) : Try[A] = {
tries.next() match {
case s: Success[A] => s
case f: Failure[A] =>
val newDefaultFailure = defaultFailure.getOrElse(f)
if(tries.hasNext) {
firstSuccessOrFirstFailure(tries, Some(newDefaultFailure))
} else {
newDefaultFailure
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment