我是scala的新手,正在寻找" scala"创建由外部源从stringed枚举中获取的正确案例类(特征符合性)的方法。由于源是外部的,因此应该验证输入是否正确,并且给定有效输入将返回正确的案例类。我认为这是一个"工厂"返回给定特征的可选案例类
示例:
trait ProcessingMechanism
case object PMv1 extends ProcessingMechanism
case object PMv2 extends ProcessingMechanism
case object PMv3 extends ProcessingMechanism
...
...
我想让工厂返回正确的ProcessingMechanism
即。
object ProcessingMechanismFactory {
... switch on the input string to return the correct mechanism???
... is there a simple way to do this?
}
答案 0 :(得分:1)
不使用宏或外部库,您可以做一些简单的事情:
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
正如对该问题的评论中所建议的那样,最好将该特征标记为sealed
。