4

I have this piece of code on the Xor object of cats

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

Now since Xor has been removed, I am trying to write something similar using Either object

Either.ensuring(name.nonEmpty, List(s"$name cannot be blank"))

but this does not work because the return type of ensuring is Either.type

I can ofcourse write an if. but I want to do the validation with the cats constructs.

4

1 回答 1

6

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)

使用猫,你可以使用ensureon Either,如果参数的顺序和缺乏柯里化不是你喜欢的:

import cats.syntax.either._

scala> e.ensure("Must be non-empty")(_.nonEmpty)
res0: Either[String,List[Int]] = Right(List(1, 2, 3))
于 2016-12-31T21:23:45.543 回答