Regarding Scala 3 enums, is there a way to override the default behavior of `valueOf` so that it doesn’t throw an exception but instead returns an Option?

Reply to this note

Please Login to reply.

Discussion

I don't think that there's a way to override it since enums are sealed classes (but I may be wrong). You can add your own method to a companion Object through

object MyEnum {

def fromString(name: String): Option[MyEnum] =

scala.util.Try(Color.valueOf(MyEnum)).toOption

}

From there you can probably use some fancy type system magic to add fromString to all subtypes of scala.reflect.Enum (warning, untested)

extension [T <: Enum](companion: T Companion) {

def fromString(name: String): Option[T] =

scala.util.Try(companion.valueOf(name)).toOption

}