Scala safe way of converting String to Enumeration value

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.

Leave a Comment