Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala safe way of converting String to Enumeration value

Tags:

scala

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?

like image 773
Nyavro Avatar asked Nov 08 '15 11:11

Nyavro


People also ask

Can you convert string to enum?

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.

How do I create an enum in Scala?

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.

What is the method to convert an enum type to a string type?

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.


2 Answers

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.

like image 192
Shadowlands Avatar answered Sep 20 '22 14:09

Shadowlands


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) } 
like image 26
Javad Avatar answered Sep 22 '22 14:09

Javad