I am currently working on a project using Scala and Play Framework 2. I want to compile some Scala code during runtime and get the result from the interpreter. I found some
The issue is in classpath in projects using Scala and Play Framework 2. It can be resolved by populating classpath from SBT to the application:
Add to build.sbt file:
val sbtcp = taskKey[Unit]("sbt-classpath")
sbtcp := {
val files: Seq[File] = (fullClasspath in Compile).value.files
val sbtClasspath : String = files.map(x => x.getAbsolutePath).mkString(":")
println("Set SBT classpath to 'sbt-classpath' environment variable")
System.setProperty("sbt-classpath", sbtClasspath)
}
compile <<= (compile in Compile).dependsOn(sbtcp)
Code:
package controllers
import play.api.mvc.{Action, Controller}
import javax.script.ScriptEngineManager
class Interpreter extends Controller {
val interpreter = new ScriptEngineManager().getEngineByName("scala")
val settings = interpreter.asInstanceOf[scala.tools.nsc.interpreter.IMain].settings
//settings.embeddedDefaults[Interpreter] // not need
//settings.usejavacp.value = true // not need
val sbtClasspath = System.getProperty("sbt-classpath")
settings.classpath.value = s".:${sbtClasspath}" // <-- this line fix the problem
def index = Action {
Ok(views.html.interpreter())
}
def interpret(input: String) = Action {
implicit request => interpreter.eval("1 to 10 foreach println")
Ok("Got: " + input)
}
}
object Interpreter
In production should be used another scenario to get a correct classpath.
Probably using a '-cp' or '-classpath' key from the command line.
I have fixed this problem by specifying scala-maven-plugin
I was using Scala 2.11.x
and if you dont specify any version in scala-maven-plugin
by default it goes with latest version which 4.4.0
Then i changed my scala-maven-plugin
to 3.2.2 and it works fine.