Here below is a case class that verifies the name
parameter is neither null
nor empty:
case class MyClass(name: String) {
require(Option(name).map(!_.isEmpty) == Option(true), "name is null or empty")
}
As expected, passing null
or an empty string to name
results in an IllegalArgumentException
.
Is it possible to rewrite the validation to get either Success
or Failure
instead of throwing an IllegalArgumentException
You can't have a constructor return something else than the class type. You can, however, define a function on the companion object to do just that:
case class MyClass private(name: String)
object MyClass {
def fromName(name: String): Option[MyClass] = {
if(name == null || name.isEmpty)
None
else
Some(new MyClass(name))
}
You can of course return a Validation
, an Either
or a Try
if you prefer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With