Search code examples
scalagenericsenumsscala-3

How to instantiate Scala 3 enum from generic type


Say I have a method in Scala 3 with the following signature:

def foo[E <: scala.reflect.Enum](str: String): E

How can I instantiate E according to str?

If for example, E is:

enum MyEnum:
  case a1, a2

Then I want the function to return MyEnum.a1 for str = "a1", MyEnum.a2 for str = "a2", and to throw an exception for other values of str.


Solution

  • Found this library which does it without runtime reflection: https://github.com/bishabosha/enum-extensions