Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala case class: how to validate constructor's parameters

Tags:

scala

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

like image 374
j3d Avatar asked Dec 09 '13 19:12

j3d


1 Answers

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.

like image 127
vptheron Avatar answered Sep 19 '22 13:09

vptheron