首先输入代码:
object MyEnums {
sealed abstract class MyEnum(val value: String)
case object First extends MyEnum("Some_ugly_looking_value1")
case object Second extends MyEnum("Some_ugly_looking_value2")
case object Third extends MyEnum("Some_ugly_looking_value3")
case object Fourth extends MyEnum("Some_ugly_looking_value4")
def fromString(value: String): Option[MyEnum] =
value match {
case First.value => Option(First)
case Second.value => Option(Second)
case Third.value => Option(Third)
case Fourth.value => Option(Fourth)
case _ => None
}
}
我在这里想要实现的是能够将来自外部的字符串值解析为上述枚举的形式。同时,如果我没有覆盖match表达式中的所有选项,我想给出详尽的模式匹配编译器警告。我在这里有什么选择?我不喜欢上面实现的方法,因为如果该枚举增加,我可能会忘记实现新的case子句...
答案 0 :(得分:3)
像这样考虑enumeratum
import enumeratum._
sealed abstract class MyEnum(override val entryName: String) extends EnumEntry
object MyEnum extends Enum[MyEnum] {
val values = findValues
case object First extends MyEnum("Some_ugly_looking_value1")
case object Second extends MyEnum("Some_ugly_looking_value2")
case object Third extends MyEnum("Some_ugly_looking_value3")
case object Fourth extends MyEnum("Some_ugly_looking_value4")
}
MyEnum.withName("Some_ugly_looking_value1") // res1: MyEnum = First
现在,当添加新的case对象时,我们不必摆弄模式匹配。