Skip to content

Instantly share code, notes, and snippets.

@wfaler
Created May 31, 2012 15:21
Show Gist options
  • Save wfaler/2844115 to your computer and use it in GitHub Desktop.
Save wfaler/2844115 to your computer and use it in GitHub Desktop.
validateanyProduct.scala
// 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 _ => {}
}
@missingfaktor
Copy link

Whenever you have isInstanceOf and asInstanceOf together, type-casing in pattern-matching can make code slightly clearer.

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 _ => ()
}

EDIT: Added the default case.

@wfaler
Copy link
Author

wfaler commented May 31, 2012

Cheers! As always, you point out good things. :)

@missingfaktor
Copy link

NP. :)

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