Scala script in 2.11

I found sample code for a Scala runtime script in response to Generating a class from a string and creating it in Scala 2.10 , however the code seems deprecated for 2.11 - I cannot find any function that matches build.setTypeSignature . Even if it worked, the code seems hard to read and follow me.

How to compile and execute Scala scripts in Scala 2.11?

Suppose I want the following:

  • define several variables (names and values)
  • compile script
  • (optional improvement) values โ€‹โ€‹of change variables
  • execute script

For simplicity, consider the following example:

I want to define the following variables (programmatically, from code, not from script text):

 val a = 1 val s = "String" 

I want the following script to be compiled and, after execution, return String from it the value "a is 1, s is String" :

 s"a is $a, s is $s" 

What should my functions look like?

 def setupVariables() = ??? def compile() = ??? def changeVariables() = ??? def execute() : String = ??? 
+3
reflection scripting scala compilation
Mar 31 '15 at 16:23
source share
1 answer

Scala 2.11 adds the JSR-223 script engine. It should provide you with the functionality you are looking for. As a reminder, like all these kinds of dynamic things, including the example in the description above, you will lose type safety. Below you can see that the return type is always an Object.

Scala REPL Example:

 scala> import javax.script.ScriptEngineManager import javax.script.ScriptEngineManager scala> val e = new ScriptEngineManager().getEngineByName("scala") e: javax.script.ScriptEngine = scala.tools.nsc.interpreter.IMain@566776ad scala> e.put("a", 1) a: Object = 1 scala> e.put("s", "String") s: Object = String scala> e.eval("""s"a is $a, s is $s"""") res6: Object = a is 1, s is String` 

An additional example as an application running under scala 2.11.6:

 import javax.script.ScriptEngineManager object EvalTest{ def main(args: Array[String]){ val e = new ScriptEngineManager().getEngineByName("scala") e.put("a", 1) e.put("s", "String") println(e.eval("""s"a is $a, s is $s"""")) } } 

For this application to work, be sure to enable the library dependency.

 libraryDependencies += "org.scala-lang" % "scala-compiler" % scalaVersion.value 
+2
Apr 03 '15 at 0:24
source share



All Articles