Skip to content

Instantly share code, notes, and snippets.

@takawitter
Last active March 12, 2021 10:38
Show Gist options
  • Save takawitter/5479445 to your computer and use it in GitHub Desktop.
Save takawitter/5479445 to your computer and use it in GitHub Desktop.
The sample code to run scala via JSR223 API. I turn usejavacp option true at line 10. Unless that you have to use http://github.com/rjolly/jarlister to list classes in scala-library.jar into MANIFEST.MF of jar that contains this ScalaTest class. I use Scala-2.11.6 to run this code.
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import scala.tools.nsc.interpreter.IMain;
import scala.tools.nsc.settings.MutableSettings.BooleanSetting;
public class ScalaTest {
public static void main(String[] args) throws Exception{
ScriptEngine engine = new ScriptEngineManager().getEngineByName("scala");
((BooleanSetting)(((IMain)engine).settings().usejavacp())).value_$eq(true);
// or
// ((scala.tools.nsc.interpreter.IMain)engine).settings().processArgumentString("-usejavacp");
engine.put("n: Int", 10);
System.out.println("---");
engine.eval("1 to n foreach print");
}
}
@doriancransac
Copy link

Hi,

Using either one of the instructions, I'm getting the following error :

Exception in thread "main" java.lang.ClassCastException: scala.tools.nsc.interpreter.Scripted cannot be cast to scala.tools.nsc.interpreter.IMain
	at TestScala.main(TestScala.java:12)

Any idea why?

@ScalaWilliam
Copy link

@DCransac I'm having this problem too. Appears that there was a change in scripting engine between 2.11 and 2.12.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment