Scala Cats:Either 上是否有确保方法?
Scala Cats: is there an ensure method on Either?
我在猫的 Xor
对象上有这段代码
Xor.right(data).ensure(List(s"$name cannot be blank"))(_.nonEmpty)
既然 Xor 已被删除,我正在尝试使用 Either 对象编写类似的东西
Either.ensuring(name.nonEmpty, List(s"$name cannot be blank"))
但这不起作用,因为 return 类型的确保是 Either.type
我当然可以写一个if。但我想用猫构造进行验证。
Xor
已从 cats 中删除,因为 Either
现在在 Scala 2.12 中是右偏的。您可以使用标准库 Either#filterOrElse
,它做同样的事情,但不是咖喱:
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)
使用猫,您可以在 Either
上使用 ensure
,如果您不喜欢参数的顺序和缺少柯里化:
import cats.syntax.either._
scala> e.ensure("Must be non-empty")(_.nonEmpty)
res0: Either[String,List[Int]] = Right(List(1, 2, 3))
我在猫的 Xor
对象上有这段代码
Xor.right(data).ensure(List(s"$name cannot be blank"))(_.nonEmpty)
既然 Xor 已被删除,我正在尝试使用 Either 对象编写类似的东西
Either.ensuring(name.nonEmpty, List(s"$name cannot be blank"))
但这不起作用,因为 return 类型的确保是 Either.type
我当然可以写一个if。但我想用猫构造进行验证。
Xor
已从 cats 中删除,因为 Either
现在在 Scala 2.12 中是右偏的。您可以使用标准库 Either#filterOrElse
,它做同样的事情,但不是咖喱:
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)
使用猫,您可以在 Either
上使用 ensure
,如果您不喜欢参数的顺序和缺少柯里化:
import cats.syntax.either._
scala> e.ensure("Must be non-empty")(_.nonEmpty)
res0: Either[String,List[Int]] = Right(List(1, 2, 3))