1

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!

John Stanford
  • 993
  • 1
  • 7
  • 18

1 Answers1

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