Skip to content

Commit ccc3877

Browse files
committed
Add or combinator to Validated. Closes #1447
1 parent bcc751f commit ccc3877

File tree

1 file changed

+13
-0
lines changed

1 file changed

+13
-0
lines changed

core/src/main/scala/cats/data/Validated.scala

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@ sealed abstract class Validated[+E, +A] extends Product with Serializable {
4444

4545
/**
4646
* Return this if it is Valid, or else fall back to the given default.
47+
* The functionality is similar to that of [[or]] except for failure accumulation.
4748
*/
4849
def orElse[EE, AA >: A](default: => Validated[EE, AA]): Validated[EE, AA] =
4950
this match {
@@ -218,6 +219,18 @@ sealed abstract class Validated[+E, +A] extends Product with Serializable {
218219
*/
219220
def ensure[EE >: E](onFailure: => EE)(f: A => Boolean): Validated[EE, A] =
220221
fold(_ => this, a => if (f(a)) this else Validated.invalid(onFailure))
222+
223+
/**
224+
* If `this` is valid return `this`, otherwise if `that` is valid return `that`, otherwise combine the failures.
225+
* This is similar to [[orElse]] except that here failures are accumulated.
226+
*/
227+
def or[EE >: E, AA >: A](that: => Validated[EE, AA])(implicit EE: Semigroup[EE]): Validated[EE, AA] = this match {
228+
case v @ Valid(_) => v
229+
case Invalid(e) => that match {
230+
case v @ Valid(_) => v
231+
case Invalid(ee) => Invalid(EE.combine(e, ee))
232+
}
233+
}
221234
}
222235

223236
object Validated extends ValidatedInstances with ValidatedFunctions{

0 commit comments

Comments
 (0)