Accepted answer

No, no such method is automatically generated. You will have to write your own fromString method. Note that you can write it more compactly as follows:

object FlagReason {
  def fromString(value: String): Option[FlagReason] = {
    Vector(Spam, Illegal, CopyRightViolation, Other).find(_.toString == value)

Alternatively you may consider using scala.Enumeration which does provide this facility.

object FlagReason extends Enumeration {
  val Spam, Illegal, CopyRightViolation, Other = Value

Then you can obtain the particular enum value with FlagReason withName "<name>", or safely as an Option with Try(FlagReason withName "<name>").toOption.


As missingfaktor points out, FlagReason withName "<name>" should do what you need. But if <name> is not a valid name, it will throw an exception. So, a slightly safer way to handle this when you are not sure if the name is valid is to use Option[FlagReason]:

scala> def parse(name: String) = FlagReason.values.find(_.toString == name)
parse: (name: String)Option[FlagReason.Value]

scala> parse("Spam")
res0: Option[FlagReason.Value] = Some(Spam)

scala> parse("NonExisting")
res1: Option[FlagReason.Value] = None

Related Query

More Query from same tag