-
-
Save seanparsons/2844124 to your computer and use it in GitHub Desktop.
validateanyProduct.scala
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
def validateProduct[T <: Product](product: T): Seq[String] = product.productIterator.flatMap{value => value match { | |
case null => Seq("null attributes are not allowed for " + product) | |
case string: String if (string.isEmpty) => Seq("Empty strings are not allowed for " + product) | |
case innerProduct: Product => validateProduct(innerProduct) | |
case _ => Seq() | |
}}.toSeq |
I've got something related in mind for Scala 2.10 using macros that does arbitrarily nested detailed comparisons, so that for:
case class Test(first: String, second: String, third: Int)
val test1 = Test("cake", "elephant", 900)
val test2 = Test("moon", "elephant", 1000)
// This method would return Seq("left.first is different to right.first.", "left.third is different to right.third.")
specialComparison(test1, test2)
With all the comparison code created and the types validated as comparable by this mechanism at compile time.
Slightly cleaner, perhaps.
def validateProduct[T <: Product](product: T): Seq[String] = product.productIterator.toSeq collect {
case null => "null attributes are not allowed for " + product
case string: String if (string.isEmpty) => "Empty strings are not allowed for " + product
case innerProduct: Product => validateProduct(innerProduct)
}
Yeah, that's much nicer.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Yup, like it! Had something like this in mind for cases where you'd want to collect all errors.