Last active
August 29, 2015 14:00
-
-
Save zhangxu/11219221 to your computer and use it in GitHub Desktop.
Option to Scalaz Validation
This file contains 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
#!/usr/bin/env scalas | |
/*** | |
scalaVersion := "2.11.0" | |
scalacOptions += "-language:_" | |
libraryDependencies += "org.scalaz" %% "scalaz-core" % "7.0.6" | |
*/ | |
import scalaz._, Scalaz._ | |
val some: Option[String] = Some("some text") | |
val none: Option[String] = None | |
case class Person(firstName: String, middleName: String, lastName: String) | |
val result = (some.toSuccess(NonEmptyList("Cannot find the first name")) |@| none.toSuccess(NonEmptyList("Cannot find the middle name")) |@| none.toSuccess(NonEmptyList("Cannot find the last"))) { | |
Person(_, _, _) | |
} | |
println("First result: ") | |
result match { | |
case Success(person) => println(person) | |
case Failure(errors) => println(errors) | |
} | |
val first = Some("John") | |
val middle = Some("Some") | |
val last = Some("Doe") | |
val result2 = (first.toSuccess(NonEmptyList("Cannot find the first name")) |@| middle.toSuccess(NonEmptyList("Cannot find the middle name")) |@| last.toSuccess(NonEmptyList("Cannot find the last"))) { | |
Person(_, _, _) | |
} | |
println("Second result: ") | |
result2 match { | |
case Success(person: Person) => println(person) | |
case Failure(errors) => println(errors) | |
} | |
val result3 = for { | |
x <- some.toSuccess(NonEmptyList("Cannot find the first name")) | |
y <- none.toSuccess(NonEmptyList("Cannot find the middle name")) | |
z <- none.toSuccess(NonEmptyList("Cannot find the last")) | |
} yield Person(x, y, z) | |
println(result3) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment