将字符串转换为枚举值的 Scala 安全方法 [英] Scala safe way of converting String to Enumeration value
本文介绍了将字符串转换为枚举值的 Scala 安全方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有枚举:
object WeekDay extends Enumeration {
type WeekDay = Value
val Mon, Tue, Wed, Thu, Fri, Sat, Sun = Value
}
我希望能够将 String 转换为 WeekDay 值,这很好:
I would like to be able to convert String to WeekDay value and this is fine with:
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?
推荐答案
你可以在枚举中添加一个方法来返回一个Option[Value]
:
You can add a method to the enumeration to return an Option[Value]
:
def withNameOpt(s: String): Option[Value] = values.find(_.toString == s)
注意:现有的 withName
方法实际上就是这样做的,然后调用 getOrElse
在else"情况下抛出异常.
Note: the existing withName
method actually does precisely this, then calls getOrElse
throwing the exception in the "else" case.
这篇关于将字符串转换为枚举值的 Scala 安全方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文