Skip to content

Instantly share code, notes, and snippets.

@leonmaia
Created August 8, 2016 12:02
Show Gist options
  • Save leonmaia/43dd4babc0242af1fa1f962877091181 to your computer and use it in GitHub Desktop.
Save leonmaia/43dd4babc0242af1fa1f962877091181 to your computer and use it in GitHub Desktop.
Scalaz validation
import scalaz.{ValidationNel, \/, \/-, Validation}
import org.joda.time.LocalDate
case class Musician(name: String, born: LocalDate)
def validate(musician: Musician): Validation[String, Musician] = {
import scalaz.Scalaz._
def validName(name: String): ValidationNel[String, String] =
if (name.isEmpty) "name cannot be empty".failure
else name.success
def validateAge(born: LocalDate): ValidationNel[String, LocalDate] =
if (born.isAfter(LocalDate.now().minusYears(12))) "too young".failure
else born.success
(validName(musician.name)
|@| validateAge(musician.born))((_, _) => musician)
}
val either: \/[String, Musician] = \/-(Musician("", LocalDate.now()))
either match {
case \/-(value) => either.@\?/(_ => validate(value))
case _ => \/-(Musician("", LocalDate.now()))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment