如何映射ValidationNel失败?

时间:2015-08-11 15:19:21

标签: validation scalaz

learned Validation有方法:-><-:来映射成功和失败。

scala> val failure: Validation[String, Unit] = "xxx".failure
failure: scalaz.Validation[String,Unit] = Failure(xxx)

scala> failure.<-:("!!!" + _)
res17: scalaz.Validation[String,Unit] = Failure(!!!xxx)

<-:

不存在ValidationNel
scala> val failure: ValidationNel[String, Unit] = "xxx".failureNel
failure: scalaz.ValidationNel[String,Unit] = Failure(NonEmptyList(xxx))

scala> failure.<-:(nel => nel + "!!!")
<console>:15: error: value <-: is not a member of scalaz.ValidationNel[String,Unit]
          failure.<-:(nel => nel + "!!!")

有趣的是,如果我将failure定义为Validation[NonEmptyList[String], Unit],它会编译。

现在我想知道是否有另一种方法可以<-:使用ValidationNel

1 个答案:

答案 0 :(得分:2)

是的,你无法为ValidationNel召唤一个Bifunctor实例,但ValidationNel实际上只是Validation [NonEmptyList [?],?]的类型别名,如你所知,它有一个Bifunctor实例。如果您将ValidationNel中的值类型强制为仅验证,那么事情就会开始起作用:

scala> import scalaz._, Scalaz._
import scalaz._
import Scalaz._

scala> val failure: Validation[String, Unit] = "xxx".failure
failure: scalaz.Validation[String,Unit] = Failure(xxx)

scala> failure.<-:("!!!" + _)
res0: scalaz.Validation[String,Unit] = Failure(!!!xxx)

scala> val failure: ValidationNel[String, Unit] = "xxx".failureNel
failure: scalaz.ValidationNel[String,Unit] = Failure(NonEmptyList(xxx))

scala> failure.<-:("!!!" <:: _)
<console>:15: error: value <-: is not a member of scalaz.ValidationNel[String,Unit]
              failure.<-:("!!!" <:: _)
                      ^

scala> val failure2: Validation[NonEmptyList[String], Unit] = failure
failure2: scalaz.Validation[scalaz.NonEmptyList[String],Unit] = Failure(NonEmptyList(xxx))

scala> failure2.<-:("!!!" <:: _)
res2: scalaz.Validation[scalaz.NonEmptyList[String],Unit] = Failure(NonEmptyList(!!!, xxx))

但是,您也可以在Validation上调用leftMap方法:

scala> failure2.leftMap("!!!" <:: _)
res3: scalaz.Validation[scalaz.NonEmptyList[String],Unit] =      Failure(NonEmptyList(!!!, xxx))

scala> failure.leftMap("!!!" <:: _)
res4: scalaz.Validation[scalaz.NonEmptyList[String],Unit] = Failure(NonEmptyList(!!!, xxx))

或使用“swapped”交换失败和成功,右键映射交换的值,然后交换它们:

scala> failure.swapped(_ :-> ("!!!" <:: _))
res5: scalaz.Validation[scalaz.NonEmptyList[String],Unit] = Failure(NonEmptyList(!!!, xxx))