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:
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?
IsDefined() method to check if a given string name or integer value is defined in a specified enumeration. Thus, the conversion of String to Enum can be implemented using the Enum. Parse ( ) and Enum.
In Scala, there is no enum keyword unlike Java or C. Scala provides an Enumeration class which we can extend in order to create our enumerations. Every Enumeration constant represents an object of type Enumeration. Enumeration values are defined as val members of the evaluation.
There are two ways to convert an Enum to String in Java, first by using the name() method of Enum which is an implicit method and available to all Enum, and second by using toString() method.
You can add a method to the enumeration to return an Option[Value]
:
def withNameOpt(s: String): Option[Value] = values.find(_.toString == s)
Note: the existing withName
method actually does precisely this, then calls getOrElse
throwing the exception in the "else" case.
Building on top of @Shadowlands 's answer, I added this method to my enum to have a default Unknown
value without dealing with options:
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) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With