Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate elements in a collection, return Failure for first invalid element [duplicate]

Tags:

scala

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)
}
like image 762
allstar Avatar asked Mar 26 '26 21:03

allstar


1 Answers

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)
like image 122
Krzysztof Atłasik Avatar answered Mar 28 '26 09:03

Krzysztof Atłasik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!