Avba
Avba

Reputation: 15266

scala "factory" design pattern for creating case object from string

I'm new to scala and looking for the "scala" way to create the correct case class (trait conforming) taken from a stringed enum by an external source. Since the source is external there should be some validation that the input is correct, and given valid input will give back the correct case class. I would assume this to be a "factory" that returns an optional case class of the given trait

Example:

trait ProcessingMechanism
case object PMv1 extends ProcessingMechanism
case object PMv2 extends ProcessingMechanism
case object PMv3 extends ProcessingMechanism
...
...

I would like to have a factory to return the correct ProcessingMechanism

i.e.

object ProcessingMechanismFactory {
   ... switch on the input string to return the correct mechanism???
   ... is there a simple way to do this?
}

Upvotes: 1

Views: 497

Answers (1)

Hosam Aly
Hosam Aly

Reputation: 42453

Without resorting to macros or external libraries, you can do something as simple as this:

object ProcessingMechanism {
  def unapply(str: String): Option[ProcessingMechanism] = str match {
    case "V1" => Some(PMv1)
    case "V2" => Some(PMv2)
    // ...
    case _ => None
  }
}

// to use it:
def methodAcceptingExternalInput(processingMethod: String) = processingMethod match {
  case ProcessingMethod(pm) => // do something with pm whose type is ProcessingMethod
}
// or simply:
val ProcessingMethod(pm) = externalString

As suggested in a comment on the question, it's better to mark the trait as sealed.

Upvotes: 1

Related Questions