Is there an easy way to execute a Scala script from within a compiled Scala application and make the variables available to the compiled application?
Could your Scala scripts expose a particular interface/trait? You may be able to do something a la ‘on the fly’ compiled plugins.
You can use scala.tools.nsc.ScriptRunner to run scripts.
You can use a singleton to store and retrieve values.
This probably does not qualify as easy:
$ cat namer.scala
import util.Properties.userName
greeting = s"Hello, $userName"
$ scala
________ ___ / / ___
/ __/ __// _ | / / / _ |
__\ \/ /__/ __ |/ /__/ __ |
/____/\___/_/ |_/____/_/ | |
|/ version 2.12.4
scala> import javax.script._
import javax.script._
scala> val engine = new ScriptEngineManager().getEngineByName("scala")
engine: javax.script.ScriptEngine = scala.tools.nsc.interpreter.Scripted@13ddaffb
scala> val b = engine.getBindings(ScriptContext.ENGINE_SCOPE)
b: javax.script.Bindings = javax.script.SimpleBindings@7fdff56b
scala> b.values
res0: java.util.Collection[Object] = []
scala> b.put("greeting", "none")
res1: Object = null
scala> b.values
res2: java.util.Collection[Object] = [none]
scala> import java.nio.file._
import java.nio.file._
scala> engine.
createBindings eval get getBindings getContext getFactory put setBindings setContext
scala> engine.eval
def eval(x$1: java.io.Reader,x$2: javax.script.Bindings): Object
def eval(x$1: String,x$2: javax.script.Bindings): Object def eval(x$1: java.io.Reader): Object
def eval(x$1: java.io.Reader,x$2: javax.script.ScriptContext): Object def eval(x$1: String,x$2: javax.script.ScriptContext): Object
def eval(x$1: String): Object
scala> engine.eval(Files.newBufferedReader(Paths.get("namer.scala")))
res3: Object = Hello, amarki
scala> b.values
res4: java.util.Collection[Object] = [Hello, amarki]
scala> b.entrySet
res5: java.util.Set[java.util.Map.Entry[String,Object]] = [greeting=Hello, amarki]