如何在ValidationNEL中遍历成功和失败结果?

时间:2014-06-03 09:57:01

标签: scala functional-programming scalaz

def myMethod: ValidationNel[String, RealResult] = {
    parsedVal = parseIt()
    parsedVal match {
        case Success(s) => s.successNel[String]
        case Failure(e) => e.getMessage.failNel[RealResult]
    }
}

在调用myMethod后,我如何处理成功和错误结果?

1 个答案:

答案 0 :(得分:0)

如下所示:

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
}

@TravisBrown建议的替代方案是在fold上使用Validation,例如:

def fnFailure(errors: List[String]) = errors.mkString(", ")

def fnSuccess(results: RealResult) = results.toString

myMethod.fold(fnFailure, fnSuccess)

如果您愿意,显然您可以在fnFailure中内联fnSuccessfold个功能。