Skip to content

Instantly share code, notes, and snippets.

@andrewconner
Created June 21, 2013 22:35
Show Gist options
  • Save andrewconner/5834845 to your computer and use it in GitHub Desktop.
Save andrewconner/5834845 to your computer and use it in GitHub Desktop.
Validating objects during a db save using `Try`
case class Employee(id: Option[Long] = None, name: String, age: Int, salary: Int)
object EmployeeRepo {
private def persist(employee: Employee): Employee = {
// persisting logic
employee.copy(id = Some(10L)) // database returns persisted id, return new object with id set
}
def save(employees: Seq[Employee])(implicit validator: Employee => Try[Employee]): Seq[Try[Employee]] = {
employees.map(validator(_).map(persist))
}
}
sealed trait ValidationException extends Throwable { val message: String }
case class BadNameException(message: String) extends ValidationException
implicit val employeeValidator = { employee: Employee =>
// validate your object, returning a Success or Failure
if(employee.name == "George") Failure(BadNameException("No George's allowed"))
else Success(employee)
}
val employeesToPersist: Seq[Employee] = ...
EmployeeRepo.save(employeesToPersist) // : Seq[Try[Employee]], which you can iterate through and deal with problems.
// http://www.scala-lang.org/archives/downloads/distrib/files/nightly/docs/library/index.html#scala.util.Try
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment