Skip to content

Instantly share code, notes, and snippets.

@leszekgruchala
Last active January 20, 2017 17:06
Show Gist options
  • Save leszekgruchala/991734522f94279c6c86ba143dce1c51 to your computer and use it in GitHub Desktop.
Save leszekgruchala/991734522f94279c6c86ba143dce1c51 to your computer and use it in GitHub Desktop.
import scalaz.{Failure, Semigroup, Success, Validation}
object ScalazCustomOps {
implicit class ScalazValidationOps[+E, +A](validation: Validation[E, A]) {
/**
* Check both validations, in case of success of both return only one success result (the latter).
* Otherwise collect failures.
*
* @tparam EE The type of the `Failure`
* @tparam AA The type of the `Success`
*/
def findOneSuccess[EE >: E, AA >: A](that: => Validation[EE, AA])
(implicit es: Semigroup[EE]): Validation[EE, AA] =
validation match {
case Failure(e) => that match {
case Failure(e0) => Failure(es.append(e, e0))
case _ => Failure(e)
}
case Success(_) => that match {
case Failure(e0) => Failure(e0)
case success => success
}
}
//Same as above but much cleaner :)
def appendFailures[EE >: E, AA >: A](that: => Validation[EE, AA])
(implicit es: Semigroup[EE]): Validation[EE, AA] = {
implicit val semigroupAA: Semigroup[AA] = Semigroup.lastSemigroup[AA]
validation +++ that
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment