Created
August 8, 2016 12:02
-
-
Save leonmaia/43dd4babc0242af1fa1f962877091181 to your computer and use it in GitHub Desktop.
Scalaz validation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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