Scala safe way of converting String to Enumeration value

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

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.

Tags:

Scala