Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save seanparsons/2844124 to your computer and use it in GitHub Desktop.
Save seanparsons/2844124 to your computer and use it in GitHub Desktop.
validateanyProduct.scala
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
@wfaler
Copy link

wfaler commented May 31, 2012

Yup, like it! Had something like this in mind for cases where you'd want to collect all errors.

@seanparsons
Copy link
Author

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.

@missingfaktor
Copy link

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)
}

@seanparsons
Copy link
Author

Yeah, that's much nicer.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment