将字符串转换为枚举值的 Scala 安全方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33593525/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Scala safe way of converting String to Enumeration value
提问by Nyavro
Suppose I have enumeration:
假设我有枚举:
object WeekDay extends Enumeration {
type WeekDay = Value
val Mon, Tue, Wed, Thu, Fri, Sat, Sun = Value
}
I would like to be able to convert String to WeekDay value and this is fine with:
我希望能够将 String 转换为 WeekDay 值,这很好:
scala> WeekDay.withName("Tue")
res10: WeekDay.Value = Tue
But if I pass some 'unknown' value, I'm getting exception:
但是,如果我传递一些“未知”值,则会出现异常:
scala> WeekDay.withName("Ou")
java.util.NoSuchElementException: None.get
at scala.None$.get(Option.scala:322)
at scala.None$.get(Option.scala:320)
at scala.Enumeration.withName(Enumeration.scala:124)
... 32 elided
Is there some elegant way of safely convert String to Enumeration value?
是否有一些优雅的方法可以安全地将 String 转换为 Enumeration 值?
回答by Shadowlands
You can add a method to the enumeration to return an Option[Value]:
您可以向枚举添加一个方法以返回一个Option[Value]:
def withNameOpt(s: String): Option[Value] = values.find(_.toString == s)
Note: the existing withNamemethod actually does precisely this, then calls getOrElsethrowing the exception in the "else" case.
注意:现有withName方法实际上就是这样做的,然后getOrElse在“else”情况下调用抛出异常。
回答by Javad Sadeqzadeh
Building on top of @Shadowlands 's answer, I added this method to my enum to have a default unknwonvalue without dealing with options:
建立在@Shadowlands 的回答之上,我将此方法添加到我的枚举中以具有默认unknwon值而不处理选项:
def withNameWithDefault(name: String): Value =
values.find(_.toString.toLowerCase == name.toLowerCase()).getOrElse(Unknown)
so the enum would look like this:
所以枚举看起来像这样:
object WeekDay extends Enumeration {
type WeekDay = Value
val Mon, Tue, Wed, Thu, Fri, Sat, Sun, Unknown = Value
def withNameWithDefault(name: String): Value =
values.find(_.toString.toLowerCase == name.toLowerCase()).getOrElse(Unknown)
}

