Skip to content

Instantly share code, notes, and snippets.

@nlinker
Created January 29, 2013 06:40
Show Gist options
  • Save nlinker/4662307 to your computer and use it in GitHub Desktop.
Save nlinker/4662307 to your computer and use it in GitHub Desktop.
How to use scalaz.Validation?
//From what I can tell the main things to tools to use are map, fold and lift.
//When you want to get something out of a validation regardless of
//whether it is a success or a failure
//(analogous to option's 'getOrElse') use fold:
class Example {
val s = 1.success[String]
// s: scalaz.Validation[String,Int] = Success(1)
val f = "fail".fail[Int]
// f: scalaz.Validation[java.lang.String,Int] = Failure(fail)
f.fold( x => "", _.toString)
// res38: java.lang.String =
s.fold( x => "", _.toString)
// res39: java.lang.String = 1
// Or you could just convert to an option:
s.toOption.getOrElse("")
// res34: Any = 1
// If you need to modify the result validation if it's a success:
s.map( _ + 1)
// res40: scalaz.Validation[String,Int] = Success(2)
// Similarly for a failure:
s.fail.map( _ + ":").validation
// res41: scalaz.Validation[java.lang.String,Int] = Success(1)
f.fail.map( _ + ":").validation
// res42: scalaz.Validation[java.lang.String,Int] = Failure(fail:)
// Lastly use lift for wrapping either the success or failure in something else:
s.lift[Option, Int]
// res43: scalaz.Validation[String,Option[Int]] = Success(Some(1))
f.fail.lift[Option, String]
// res45: scalaz.Validation[Option[String],Int] = Failure(Some(fail))
//Using these methods rather than pattern matching does seem to make for
//cleaner code.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment