dimanche 22 novembre 2020

Run Macro to generate code from parent class in Scala

I have a macro that I use to generate some code to call methods dynamically. The macro is more complex than this, but for simplicity let's say it works something like this

def myMacro[T]: Seq[MethodName]

so than when called on

class Hello {
  def one(a: Int, b: UserId): String = a.toString + b.id

  def two(c: Option[Int]): String = ""

  def three(d: Seq[Int], f: Set[Int]): String = ""
}
println(myMacro[Hello]) // Seq("one", "two", "three")

I need this macro to generate code for an internal framework we use at Candu, but I need to be able to call it from the parent's class. So what I want to achieve is:

trait Superclass {
  def aFakeMethod: String = ""

  val methods = myMacro[Self] // FIXME! self is not defined here...
}

class Hello extends Superclass {
  def one(a: Int, b: UserId): String = a.toString + b.id

  def two(c: Option[Int]): String = ""

  def three(d: Seq[Int], f: Set[Int]): String = ""
}
val hi = new Hello
println(hi.methods) // Seq("one", "two", "three")

Because the high number of classes in the framework, modifying the api between Hello and Superclass is very expansive. So I would need a way to do this without changing code in Hello

Any suggestions on how this could be achieved?





Aucun commentaire:

Enregistrer un commentaire