1

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?
}
Avba
  • 14,822
  • 20
  • 92
  • 192
  • 1
    If you have `sealed trait` you can use the https://stackoverflow.com/q/13671734 question might help. If you are looking for a library, probably https://github.com/lloydmeta/enumeratum is the most popular nowadays. – Gábor Bakos Dec 10 '17 at 08:38

1 Answers1

1

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.

Hosam Aly
  • 41,555
  • 36
  • 141
  • 182