0

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("test@gmail.com")"""
val tree = toolbox.parse(codeToCompile)
val binary = toolbox.compile(tree)()

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

user3476509
  • 171
  • 10

1 Answers1

0

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}("test@gmail.com")"""
val myAuth = toolbox.eval(codeToCompile1) // Authentication(test@gmail.com)
Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66