mardi 25 janvier 2022

Scala reflection: how do I define a case class at runtime and then reference to it?

I would like to define a case class at run-time, like for example

val tb = universe.runtimeMirror(getClass.getClassLoader).mkToolBox()
val myClass: ClassDef = q"case class Authentication(email: String)".asInstanceOf[ClassDef]
val definedClass  = tb.define(myClass)

And then being able to refer to it in another reflection

  // Actor code that recognise the defined case object
  val actorCode = q"""
  import akka.actor._
  object HelloActor {
    def props() = Props(new HelloActor())
  }
  class HelloActor() extends Actor {
    def receive = {
      case $definedClass(emailParam)  => println("case object instance has been received!")
      case _       => println("None received!")
    }
  }
  return HelloActor.props()
  """

Any idea on how to do the trick ?





Aucun commentaire:

Enregistrer un commentaire