j3d
j3d

Reputation: 9734

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

Upvotes: 18

Views: 17014

Answers (1)

vptheron
vptheron

Reputation: 7466

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.

Upvotes: 24

Related Questions