Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add valueOr to Validated, analog to Xor.valueOr #1121

Merged
merged 1 commit into from
Jun 15, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions core/src/main/scala/cats/data/Validated.scala
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,11 @@ sealed abstract class Validated[+E, +A] extends Product with Serializable {
*/
def getOrElse[B >: A](default: => B): B = fold(_ => default, identity)

/**
* Return the Valid value, or the result of f if Invalid
*/
def valueOr[B >: A](f: E => B): B = fold(f, identity)

/**
* Is this Valid and matching the given predicate
*/
Expand Down Expand Up @@ -203,6 +208,8 @@ sealed abstract class Validated[+E, +A] extends Product with Serializable {
case Invalid(e) => Valid(e)
}

def merge[EE >: E](implicit ev: A <:< EE): EE = fold(identity, ev.apply)

/**
* Ensure that a successful result passes the given predicate,
* falling back to an Invalid of `onFailure` if the predicate
Expand Down
6 changes: 6 additions & 0 deletions tests/src/test/scala/cats/tests/ValidatedTests.scala
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,12 @@ class ValidatedTests extends CatsSuite {
}
}

test("valueOr consistent with swap then map then merge") {
forAll { (v: Validated[String, Int], f: String => Int) =>
v.valueOr(f) should === (v.swap.map(f).merge)
}
}

test("toEither then fromEither is identity") {
forAll { (v: Validated[String, Int]) =>
Validated.fromEither(v.toEither) should === (v)
Expand Down