Skip to content

Commit

Permalink
Add Validated.cond and Validated.condNel (#1998)
Browse files Browse the repository at this point in the history
  • Loading branch information
andyscott authored and kailuowang committed Oct 31, 2017
1 parent af7354c commit f3981dd
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
14 changes: 14 additions & 0 deletions core/src/main/scala/cats/data/Validated.scala
Original file line number Diff line number Diff line change
Expand Up @@ -587,4 +587,18 @@ private[data] trait ValidatedFunctions {
* Converts an `Ior[A, B]` to a `Validated[A, B]`.
*/
def fromIor[A, B](ior: Ior[A, B]): Validated[A, B] = ior.fold(invalid, valid, (_, b) => valid(b))

/**
* If the condition is satisfied, return the given `B` as valid,
* otherwise return the given `A` as invalid.
*/
final def cond[A, B](test: Boolean, b: => B, a: => A): Validated[A, B] =
if (test) valid(b) else invalid(a)

/**
* If the condition is satisfied, return the given `B` as valid NEL,
* otherwise return the given `A` as invalid NEL.
*/
final def condNel[A, B](test: Boolean, b: => B, a: => A): ValidatedNel[A, B] =
if (test) validNel(b) else invalidNel(a)
}
12 changes: 12 additions & 0 deletions tests/src/test/scala/cats/tests/ValidatedSuite.scala
Original file line number Diff line number Diff line change
Expand Up @@ -267,4 +267,16 @@ class ValidatedSuite extends CatsSuite {
}
}
}

test("cond consistent with Either.cond + toValidated") {
forAll { (cond: Boolean, s: String, i: Int) =>
Validated.cond(cond, s, i) should === (Either.cond(cond, s, i).toValidated)
}
}

test("condNel consistent with Either.cond + toValidatedNel") {
forAll { (cond: Boolean, s: String, i: Int) =>
Validated.condNel(cond, s, i) should === (Either.cond(cond, s, i).toValidatedNel)
}
}
}

0 comments on commit f3981dd

Please sign in to comment.