Skip to content

Instantly share code, notes, and snippets.

@j5ik2o
Last active December 19, 2015 04:29
Show Gist options
  • Select an option

  • Save j5ik2o/5897977 to your computer and use it in GitHub Desktop.

Select an option

Save j5ik2o/5897977 to your computer and use it in GitHub Desktop.
package com.github.j5ik2o.scalaz
import scalaz._
import Scalaz._
class Request(map: Map[String, Any]) {
def apply(name: String): Any = map(name)
}
case class PersonForm(name: String, age: Int)
object PersonForm {
private def validateName(name: String): ValidationNel[Throwable, String] =
if (name.size > 0)
name.successNel
else
new Exception("name is empty").failureNel
private def validateAge(age: Int): ValidationNel[Throwable, Int] =
if (age > 20)
age.successNel
else
new Exception("age is invalid").failureNel
private def validate(name: String, age: Int): ValidationNel[Throwable, PersonForm] =
(validateName(name) |@| validateAge(age))(PersonForm.apply _)
def validate(request: Request): ValidationNel[Throwable, PersonForm] = {
validate(
request("name").asInstanceOf[String],
request("age").asInstanceOf[Int]
)
}
}
object Main extends App {
val personForm1 = PersonForm.validate(new Request(Map("name" -> "kato", "age" -> 21)))
personForm1 match {
case Success(personForm) => println(personForm)
case Failure(ex) => ex.foreach(println)
}
val personForm2 = PersonForm.validate(new Request(Map("name" -> "", "age" -> 0)))
personForm2 match {
case Success(personForm) => println(personForm)
case Failure(ex) => ex.foreach(println)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment