Could someone give a simple example of how I'd use scala.tools.nsc to compile a Scala class during runtime from within a JVM? I'm experimenting with some dynamic behavior where I want to be able to compile Scala classes during runtime, then load and use them. I'm mostly interested in compiling objects with pure functions of primitive types (Doubles, Floats, etc). Thanks!
Asked
Active
Viewed 73 times
1
-
sounds like you're looking for `scala.tools.reflect.ToolBox` – Seth Tisue Oct 12 '18 at 18:51
1 Answers
0
The comment about scala.tools.reflect.Toolbox
put me on the right track and I ended up being able to answer my own question. Something like this is what I was looking for:
import scala.reflect.runtime._
import scala.reflect.runtime.universe._
import scala.tools.reflect.ToolBox
object Main extends App {
val cm = universe.runtimeMirror(getClass.getClassLoader)
val toolBox = cm.mkToolBox()
val f = toolBox.eval(toolBox.parse("""(x:Double) => x*x"""))
f match {
case f1:scala.Function1[Double, Any] =>
println(f1(4.4))
case _ =>
throw new Exception("Expected a Function1[Double,Any] but got something else")
}
}

John Stanford
- 993
- 1
- 7
- 18