From b91aa21721d63b6b919da7a29e9bf85e6dfdbf4f Mon Sep 17 00:00:00 2001 From: Michael Zuber Date: Wed, 2 Nov 2016 09:36:14 -0400 Subject: [PATCH] Changed Validated orElse functionality to accumulate failures. Also added orThen combinator to preserve old functionality. Closes #1447 --- core/src/main/scala/cats/data/Validated.scala | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/core/src/main/scala/cats/data/Validated.scala b/core/src/main/scala/cats/data/Validated.scala index d55915dab5c..87931ded51a 100644 --- a/core/src/main/scala/cats/data/Validated.scala +++ b/core/src/main/scala/cats/data/Validated.scala @@ -44,13 +44,26 @@ sealed abstract class Validated[+E, +A] extends Product with Serializable { /** * Return this if it is Valid, or else fall back to the given default. + * The functionality is similar to that of [[orElse]] except for failure accumulation. */ - def orElse[EE, AA >: A](default: => Validated[EE, AA]): Validated[EE, AA] = + def orThen[EE, AA >: A](default: => Validated[EE, AA]): Validated[EE, AA] = this match { case v @ Valid(_) => v case Invalid(_) => default } + /** + * If `this` is valid return `this`, otherwise if `that` is valid return `that`, otherwise combine the failures. + * This is similar to [[orThen]] except that here failures are accumulated. + */ + def orElse[EE >: E, AA >: A](that: => Validated[EE, AA])(implicit EE: Semigroup[EE]): Validated[EE, AA] = this match { + case v @ Valid(_) => v + case Invalid(e) => that match { + case v @ Valid(_) => v + case Invalid(ee) => Invalid(EE.combine(e, ee)) + } + } + /** * Converts the value to an Either[E, A] */