I'm creating an enum value dynamically. I have a type of the enum (not the object itself) and a string representing a valid value, e.g. "Red" for Color.Red.
// T is Color (enum). I've discovered the valueOf() method lives in the companion object
val sym = TypeRepr.of[T].classSymbol.get.companionClass
// Try to invoke the valueOf() method on the enum with the value, enumValue ("Red")
Apply(Select.unique(New(TypeIdent(sym)), "valueOf"), List('{ enumValue }.asTerm)).asExprOf[T]
It compiles but is deeply unhappy when run. Doesn't like New there, which makes sense because we don't "new" objects.
What's the proper way to invoke valueOf dynamically in a macro?
prints:
after removing
Inline
garbadge:To construct this tree (your problem seem to be
Ident
) I guess we can use:Usage of
Ref
is the same whether you construct anything dynamically or in compile time.When I need to handle sealed hierarchies "statically" I use the following apprach:
Type
s intoExpr
scase class
es (create None for the code above)(Actually, Scala 3 macros treat Java enums the same as Scala 3 enums without any parenthesis, so
|| isJavaEnumValue
is kinda redundant - you could remove it and it should still works with Scala 2'ssealed
hierarchy ofcase object
s, Scala 3'senum
s AND Javaenum
s).As you can see in both cases, dynamical and statical, when I need to access case object/parameterless case in Scala 3's enum/Java's enum/companion object's method I am using
Ref <: Term
to turnSymbol
intoTerm
(and it will beIdent
internally).