Scala case class: how to validate constructor's parameters

scala

Solution

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.

Problem

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`

Original source