Last active
March 12, 2021 10:38
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"); | |
} | |
} |
I updated the code to use binding with type -> engine.put("n: Int", 10);
I found it accidentally 😄
@takawitter Thank you very much for this helpful gist! This is the only place I found with details on how to call the Scala script engine from plain Java, rather than from other Scala code. You made all my problems go away: scijava/scripting-scala@1950c73 🍻
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?
@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
Thanks for your comment, rjolly!
For the classpath, even using manifest, a problem still exists when we are developing web application. The web application places classes to its WEB-INF/class folder and jars to its WEB-INF/lib folder, and scala-jsr223 doesn't have the function to recognize those classes (and no guarantee for the web-app container to read manifest).
I could use binded variable through bindings such like:
Let me note requirements about variable bindings of scala-jsr223.
Anyway, I'm looking forward to next release and will test jsr223 compliant when its available.
thanks.