Created
October 14, 2015 04:34
-
-
Save thsutton/a03c9a843b208fe1c082 to your computer and use it in GitHub Desktop.
Simple validation thing
This file contains hidden or 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
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