Scala Cats: is there an ensure method on Either?

1.6k views Asked by At

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.

1

There are 1 answers

0
Michael Zajac On BEST ANSWER

Xor was removed from cats because Either is now right-biased in Scala 2.12. You can use the standard library Either#filterOrElse, which does the same thing, but is not curried:

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)

Using cats, you can use ensure on Either, if the order of the parameters and lack of currying isn't to your liking:

import cats.syntax.either._

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