j3d j3d - 1 month ago 9
Scala Question

Scala case class: how to validate constructor's parameters

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

Answer

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.

Comments