how do i manually construct a scala runtime ast that instantiates a class?

Besides extractor’s apply metod accepting a Name

abstract class IdentExtractor {
  def apply(name: Name): Ident
  //...
}

https://github.com/scala/scala/blob/2.13.x/src/reflect/scala/reflect/api/Trees.scala#L1787

there is also factory method accepting a Symbol

def Ident(sym: Symbol): Ident

https://github.com/scala/scala/blob/2.13.x/src/reflect/scala/reflect/api/Trees.scala#L2237

Try

val actualTree = Apply(
  Select(
    New(Ident(typeOf[Foo].typeSymbol)),
    termNames.CONSTRUCTOR
  ),
  List(
    Literal(Constant(1))
  )
)

println(ru.showRaw(actualTree)) 
//Apply(Select(New(Ident(my.package.Foo)), termNames.CONSTRUCTOR), List(Literal(Constant(1))))

println(toolbox.typecheck(actualTree).tpe) // my.package.Foo

Quasiquotes and reify/splice are preferable ways to construct trees. So you should provide more details why q"new my.package.Foo(1)" and ru.reify { new Foo(1) }.tree are not enough for your use case. Normally it’s not necessary to build identical trees, it’s enough to build trees that behave as desired (but there are exceptions).

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top