I have a macro function that takes a type T
and should generate an instance of type T
. So it looks something like this:
def clientImpl[T: Type](using Quotes): Expr[T]
Now I would like to create a new object of type T. In scala 2 macros, I wrote this:
q"""
new ${weakTypeTag.tpe.finalResultType} {
...
}
"""
How could I do the same in scala 3 macros?
I have failed in creating the tree myself with TypeDef
or ClassDef
.
1 Like
Apply(
Select(
New(TypeTree.of[a]),
TypeRepr.of[a].typeSymbol.primaryConstructor
),
Nil
).asExprOf[a]
Where you replace a
with T
should get you what you want.
Thank you, that is useful snippet! Though, I realize, my question might be a bit unclear.
The type I have is a trait
and not a class
- so there sadly is no primary constructor. I want to create an anonymous class, like:
new Trait {
def foo = 1
}
Which could be translated to:
class Anon extends Trait {
def foo = 1
}
new Anon
As far as I’m aware, extending or modifying classes/traits/etc through compile time reflection is currently unsupported in Scala 3. At least, that’s what I was told when I last inquired about it (about a month ago). I think there was a ticket on the dotty repo to add support for such though.
If I find a way, I’ll let you know, and I hope you find a way, cause it would be helpful for me.
Good hint with the issue! These seem to be relevant: https://github.com/lampepfl/dotty/issues/11685 and https://github.com/lampepfl/dotty-feature-requests/issues/153
I have answered there with the workaround I have tried in the current API.