Created
May 31, 2012 15:21
-
-
Save wfaler/2844115 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
// modify to collect errors, use Either or whatever floats your boat, just an example that throws | |
// IllegalArgumentException on the first null or empty String it encounters, if there is one. | |
// Works for any case class or collection such as List. | |
def validateProduct[T <: Product](product: T): Unit = product.productIterator foreach { | |
case null => throw new IllegalArgumentException("null attributes are not allowed for " + product) | |
case x: String if x.isEmpty => throw new IllegalArgumentException("Empty strings are not allowed for " + product) | |
case x: Product => validateProduct(x) | |
case _ => {} | |
} |
Cheers! As always, you point out good things. :)
NP. :)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Whenever you have
isInstanceOf
andasInstanceOf
together, type-casing in pattern-matching can make code slightly clearer.EDIT: Added the
default
case.