简体   繁体   中英

how to traverse both success and fail results in ValidationNEL?

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?

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 eg:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM