Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scala 3 macro how to implement generic trait

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

like image 741
jilen Avatar asked Jan 04 '21 10:01

jilen


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

Method Override with Scala 3 Macros (since Scala 3.1.3)

like image 174
Dmytro Mitin Avatar answered Nov 12 '22 04:11

Dmytro Mitin