Skip to content

Instantly share code, notes, and snippets.

@thsutton
Created October 14, 2015 04:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thsutton/a03c9a843b208fe1c082 to your computer and use it in GitHub Desktop.
Save thsutton/a03c9a843b208fe1c082 to your computer and use it in GitHub Desktop.
Simple validation thing
sealed abstract class Validation[T] {
def must(p: (T => Boolean), error: String): Validation[T]
}
object Validation {
def apply[T](value: T): Validation[T] = Valid(value)
}
case class Invalid[T](value: T, errors: List[String]) extends Validation[T] {
def must(p: (T => Boolean), error: String): Validation[T] =
if (p(value)) this
else Invalid(value, error +: errors)
}
case class Valid[T](value: T) extends Validation[T] {
def must(p: (T => Boolean), error: String): Validation[T] =
if (p(value)) this
else Invalid(value, List(error))
}
object Test extends App {
Validate("Hello").must( (_.length > 0), "No empty strings, please")
.must( (_ contains "ring"), "If you liked it you should have put a ring in it")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment