Global Feed Post Login
Replying to Avatar Anthony Accioly

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

}

Avatar
Matej Cerny 10mo ago

Yeah, it's really hard to find new enums useful, not only because of this, but also because of the missing support for hierarchy 😏

Reply to this note

Please Login to reply.

Discussion

No replies yet.