2

If I have some validation function:

def validateOne(a: A): Try[A]

And I now want to validate a collection of A by using the validateOne function

def validateAll(all: List[A]): Try[List[A]]

Is there a nice way to return a Failure as soon as the first element is found to be invalid?

The way I'm doing it now is by calling get after validating each element. For the first element where validateOne returns Failure, get throws the wrapped exception...which I catching re-wrap:

def validateAll(all: List[A]): Try[List[A]] = try {
  all.map(a => validateOne(a).get)
} catch {
  case e: MyValidationException => Failure(e)
}
allstar
  • 1,155
  • 4
  • 13
  • 29

1 Answers1

8

You could easily transform List[Future[A]] to Future[List[A]] with Future.sequence. Unfortunately the standard library doesn't provide a similar method for Try.

But you could create your own tail-recursive, failing fast function to iterate over results:

def validateAll[A](all: List[A]): Try[List[A]] = {

  //additional param acc(accumulator) is to allow function to be tail-recursive
  @tailrec
  def go(all: List[A], acc: List[A]): Try[List[A]] =
    all match {
      case x :: xs =>
        validateOne(x) match {
          case Success(a) => go(xs, a :: acc)
          case Failure(t) => Failure(t)
        }
      case Nil => Success(acc)
    }

  go(all, Nil)
}

If you're using cats in your stack you could also use traverse (traverse is map + sequence):

import cats.implicits._

def validateAll2[A](all: List[A]): Try[List[A]] = all.traverse(validateOne)
Krzysztof Atłasik
  • 21,985
  • 6
  • 54
  • 76