Using Scala as a Java ScriptEngine

Long time Java user, Scala novice, working on a large enterprise codebase that contains both Java and Scala code.

I’m trying to run a Scala script contained in a String from deep inside some Java code.

This successfully runs a Scala script:

ScriptEngine engine = new ScriptEngineManager().getEngineByName("scala");
Object resultObj = engine.eval(scalaScriptCodeString);

but there are issues with class references; our internal libraries aren’t seen by Scala.

I found a couple chunks of old sample code online that suggested the Scala scripting engine could have its classpath adjusted after loading; but neither of these examples work now:

((IMain)engine).settings().classpath().append(System.getProperty("java.class.path"));

(BooleanSetting)(((IMain)engine).settings().usejavacp())).value_$eq(true);

They don’t compile because engine can no longer be cast to IMain; I suspect maybe this worked in an earlier version of Scala…?

And, in any case, I’m not sure those would have helped; ideally we’d like to have the script run with the same ClassLoader environment as the code instantiating the ScriptEngine.

Our library classes are there; I can instantiate our libraries from Scala using Java reflection:

Class.forName("our.library.Thing").newInstance()  // works!

but I can’t reference them from Scala:

import our.library.Thing            // fails
val foo = new our.library.Thing()   // also fails

I tried looking at the source of scala.tools.nsc.interpreter.Scripted, but my knowlede of Scala is’t really sufficient for that, plus I don’t know anything about the compiler internals. I see some stuff about imports and dynamic binding in the code, but don’t really know enough to go from there.

I tried looking at the engine instance with Java introspection, but didn’t find anything particularly helpful.

So, my questions are:

  1. Is there a way to run a Scala script from Java that gives the Scala code easy access to our existing Java libraries? (and to our existing Scala libraries too)

  2. Is there a good place to find up to date documentation and examples on how to use Scala as a Java ScriptEngine? Everything I’ve found seems out of date and/or out of sync with the latest version of Scala.

The current goal is just proof-of-concept; the eventual goal would be to run little DSL scripts fetched from someplace (as opposed to compiled into our code). It would potentially be feasible to instantiate and run the scripts by writing a Scala library rather than using the Java ScriptEngine framework, if the ScriptEngine framework is too limiting for whatever reason. But ideally, we’d like to be able to interact with other script engines as well.

Thanks!