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?



Read more here: https://stackoverflow.com/questions/64958194/run-macro-to-generate-code-from-parent-class-in-scala

Content Attribution

This content was originally published by mre at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: