Scala猫:是否有任何一种确保方法



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

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

现在由于XOR已被删除,我正在尝试使用任何一个对象

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

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

我当然可以写一个if。但是我想用猫构造进行验证。

Xor从猫中删除,因为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))

最新更新