how to traverse both success and fail results in ValidationNEL?
-
21-12-2019 - |
Question
def myMethod: ValidationNel[String, RealResult] = {
parsedVal = parseIt()
parsedVal match {
case Success(s) => s.successNel[String]
case Failure(e) => e.getMessage.failNel[RealResult]
}
}
How do I now after calling myMethod
handle both success and error results?
Solution
How about something like the following?
import scalaz.{Success => SuccessZ, Failure => FailureZ} //to avoid any potential conflicts with scala.util equivalents
myMethod match {
case FailureZ(errors) =>
//TODO handle your errors here
case SuccessZ(results) =>
//TODO handle your results here
}
An alternative as suggested by @TravisBrown, is to use fold
on the Validation
e.g.:
def fnFailure(errors: List[String]) = errors.mkString(", ")
def fnSuccess(results: RealResult) = results.toString
myMethod.fold(fnFailure, fnSuccess)
Obviously you could inline the fnFailure
and fnSuccess
functions in the fold
if you prefer.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow