Cats: Add Validated.ensure[EE >: E](onFailure: A => EE)(f: A => Boolean): Validated[EE, A]

Created on 9 Mar 2017  路  2Comments  路  Source: typelevel/cats

Add a cats.data.Validated.ensure(...) with this signature:

ensure[EE >: E](onFailure: A => EE)(f: A => Boolean): Validated[EE, A].

To be able to extract informations from A to construct the EE in the failure case with the onFailure function.

val personValidated = ???

personValidated.ensure(p => s"Too young (age: ${p.age} < 18)")(_.age >= 18)
low-hanging fruit

Most helpful comment

Would be nice to have the same feature on Either:

def ensure[AA >: A](onFailure: B => AA)(f: B => Boolean): Either[AA, B]

so that one can write

type ErrorWith[A] = Either[String, A]
val n: ErrorWith[Int] = Right(6)
n.map(_*100).ensure(n => s"$n is less than 1000")(_ >= 1000)

Same addition should also be provided for EitherT.

All 2 comments

I can make a PR soon :)

Would be nice to have the same feature on Either:

def ensure[AA >: A](onFailure: B => AA)(f: B => Boolean): Either[AA, B]

so that one can write

type ErrorWith[A] = Either[String, A]
val n: ErrorWith[Int] = Right(6)
n.map(_*100).ensure(n => s"$n is less than 1000")(_ >= 1000)

Same addition should also be provided for EitherT.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

SimY4 picture SimY4  路  4Comments

mcanlas picture mcanlas  路  4Comments

durban picture durban  路  4Comments

chuwy picture chuwy  路  4Comments

adelbertc picture adelbertc  路  5Comments