Scripting Scala – JSR-223

With the release of Scala 2.11 it became fully JSR-223 compliant scripting language for Java. JSR-223 is the community request to allow scripting language to have an interface to Java and to allow Java to use the scripting language inside of applications.

In Java 8 the Nashorn scripting engine was released as a native component of the JDK to support JavaScript with applications. This is possible through another JSR in Java 7 – namely JSR-229, which brings support for invoke dynamics, a way to support dynamic programming by the Java byte code compiler. Nashorn can be seen as a proof of concept of this newly added functionality.

Running Scala Script in Java Application

Let’s make a simple example to execute Scala as a script inside of a Java application.

We need to import and initialize the script engine like this:

With  ScriptEngineManager().getEngineByName("scala")  a matching script engine is looked up. This just gives us the engine but not the required libraries and hooks to really execute a script.

There is one thing to note about the way Scala loads the required standard classes for the JVM. In case of the execution of scala standard Scala libraries are placed in the classpath of the JVM. This would not be the case here. You can read this for a reference. Trying to run a sample class would result in the following exception:

We can work around this by using the scala java tools helping us to load the standard Scala libraries into the JVM classpath. This is one way to make our Scala script work:

The other is to simply execute the code with the following option:

The complete script is this:

Compiling and running this is pretty straight forward as we do need the Scala libraries they get places into the classpath.

Compiling:

Running:

Further Readings

1 thought on “Scripting Scala – JSR-223”

Leave a Reply