Last active
February 23, 2017 15:52
-
-
Save atamborrino/44b1d3f22f4df507a99e619a11657d77 to your computer and use it in GitHub Desktop.
Validation "or" operator with error accumulation for Scalactic
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import org.scalactic._ | |
| import org.scalactic.Accumulation._ | |
| trait Error | |
| type Errors = Every[Error] | |
| case object AnError extends Error | |
| object ValidationImplicits { | |
| implicit class ValidationOps[E](val validLeft: Validation[Every[E]]) extends AnyVal { | |
| def or(validRight: Validation[Every[E]]): Validation[Every[E]] = { | |
| (validLeft, validRight) match { | |
| case (Pass, Pass) => Pass | |
| case (Fail(_), Pass) => Pass | |
| case (Pass, Fail(_)) => Pass | |
| case (Fail(errorsLeft), Fail(errorsRight)) => Fail(errorsLeft ++ errorsRight) | |
| } | |
| } | |
| } | |
| } | |
| import ValidationImplicits._ | |
| def validate1(s: String): Validation[Errors] = Pass | |
| def validate2(s: String): Validation[Errors] = Fail(One(AnError)) | |
| def sOrError = Good("foo") | |
| // Usage: | |
| for { | |
| s <- sOrError | |
| if validate1(s) or validate2(s) | |
| } yield s | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment