38

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?

0

2 Answers 2

61

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Wish this was part of the standard library, it's idiomatic Scala after all to have a safe way of doing things.
Might want to consider doing a case-insensitive comparison check
Doesn't work since Java 9. _ can no longer be used as an identifier.
11

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)
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.