[Scala Toolbox]: Compile a Case Class at run-time and then instantiate it

121 views Asked by At

I'm trying to define a case class using Scala Reflection Toolbox and to instantiate it. What is the best way to do it?

At the moment I do

val codeToCompile = q"""case class Authentication(email:String)"""
val tree = toolbox.parse(codeToCompile) 
val classDefinition : ClassDef = tree.asInstanceOf[ClassDef]
val definedClass = toolbox.define(classDefinition)

I would like to use the constructor of the case class to instantiate it at run-time after I have defined it into the Toolbox, Like

val codeToCompile = q"""val myAuth = Authentication("[email protected]")"""
val tree = toolbox.parse(codeToCompile)
val binary = toolbox.compile(tree)()

I get the error: Authentication not found ... How can I do it ?

1

There are 1 answers

0
Dmytro Mitin On

Firstly, s interpolator generates strings, q interpolator generates trees. So either use q"..." without .parse or use s"..." with .parse.

Secondly, make use of ClassSymbol definedClass, which you have.

Thirdly, .apply is a companion-object method. So use .companion.

Forthly, there is not much sense in defining a local variable in single-line q"val x = ???" with toolbox, anyway it will be hard to use this TermSymbol later (on contrary to ClassSymbol).

Try

val codeToCompile = s"""case class Authentication(email:String)"""
val tree = toolbox.parse(codeToCompile)
val classDefinition : ClassDef = tree.asInstanceOf[ClassDef]
val definedClass = toolbox.define(classDefinition)

val codeToCompile1 = q"""${definedClass.companion}("[email protected]")"""
val myAuth = toolbox.eval(codeToCompile1) // Authentication([email protected])