Scala Cats:在Aither上有一个确保方法吗?

时间:2016-12-31 20:13:53

标签: scala scala-cats

我在猫的Xor对象上有这段代码

Xor.right(data).ensure(List(s"$name cannot be blank"))(_.nonEmpty)

现在,由于Xor已被删除,我正在尝试使用Either object

编写类似的内容
Either.ensuring(name.nonEmpty, List(s"$name cannot be blank"))

但这不起作用,因为确保的返回类型是Either.type

我可以写一个if。但我想用猫结构进行验证。

1 个答案:

答案 0 :(得分:5)

Xor已从猫中移除,因为Either现在在Scala 2.12中是正确的偏见。您可以使用标准库Either#filterOrElse,它执行相同的操作,但不是curry:

val e: Either[String, List[Int]] = Right(List(1, 2, 3))
val e2: Either[String, List[Int]] = Right(List.empty[Int])

scala> e.filterOrElse(_.nonEmpty, "Must not be empty")
res2: scala.util.Either[String,List[Int]] = Right(List(1, 2, 3))

scala> e2.filterOrElse(_.nonEmpty, "Must not be empty")
res3: scala.util.Either[String,List[Int]] = Left(Must not be empty)

使用猫,你可以ensure使用Either,如果参数的顺序和缺乏currying不符合你的喜好:

import cats.syntax.either._

scala> e.ensure("Must be non-empty")(_.nonEmpty)
res0: Either[String,List[Int]] = Right(List(1, 2, 3))