scala 3 macro how to implement generic trait

Viewed 280

I want to implement a proxy of some trait A (e.g. delegates method call to some rpc call), like this

   def clientProxy[A](using Type[A], Quotes): Expr[A] = {
    import quotes.reflect._
    val defTrees: List[Tree] = TypeRepr.of[A].typeSymbol.memberFields.collect {
      case mf if mf.isDefDef =>
        ???
    }

    val exprs = Expr.ofList(defTrees.map(_.asExpr))
    '{
      new A {
        $exprs
      }
    }
  }

But the compiler complains

A is not a class type

1 Answers

If A were a class you could try to replace

'{
  new A {
    $exprs
  }
}

with

Apply(
  Select.unique(New(TypeTree.of[A]), "<init>"),
  defTrees.map(_.asExpr.asTerm)
).asExprOf[A]

(Scala 3.0.0-RC1-bin-20210106-e39b79e-NIGHTLY)

How to access parameter list of case class in a dotty macro

Now since A is a trait, I guess you should define a class implementing this trait and try similar thing for this class.

Related