Skip to content

Instantly share code, notes, and snippets.

@JoolsF
Last active May 22, 2019 08:47
Show Gist options
  • Save JoolsF/caf69c1fe661fb9bc244287f1eb46d58 to your computer and use it in GitHub Desktop.
Save JoolsF/caf69c1fe661fb9bc244287f1eb46d58 to your computer and use it in GitHub Desktop.
Cats Validated example 1
import cats.data._
import cats.implicits._
//Left side is better as non empty list
type MyValidation[A] = Validated[Vector[String], A]
case class Person(name: String, age: Int)
def validateName(name: String): MyValidation[String] =
if (name.isEmpty) {
Validated.invalid(Vector("Name must not be empty"))
} else {
Validated.valid(name)
}
def validateAge(age: Int): MyValidation[Int] =
if (age < 0) {
Validated.invalid(Vector("Age must be greater than zero"))
} else {
Validated.valid(age)
}
def validateAndCreatePerson(name: String, age: Int): Either[Vector[String], Person] =
(
validateName(name),
validateAge(age)
).mapN(Person.apply).toEither
validateAndCreatePerson("", -1)
//res0: Either[Vector[String],Person] = Left(Vector(Name must not be empty, Age must be greater than zero))
validateAndCreatePerson("Julian", 20)
// Either[Vector[String],Person] = Right(Person(Julian,20))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment