How to use JSR-223 to get Scala interpreter in sbt console?

旧街凉风 提交于 2019-11-29 04:51:06

You can cast your engine to scala.tools.nsc.interpreter.IMain, which will give you an access to the settings. Then you can use embeddedDefaults to set a classpath as it was mentioned in the FAQ. Just do it before call to the eval method.

val engine = new javax.script.ScriptEngineManager().getEngineByName("scala")
val settings = engine.asInstanceOf[scala.tools.nsc.interpreter.IMain].settings
// MyScalaClass is just any class in your project
settings.embeddedDefaults[MyScalaClass]

Given that you should be able to run eval, e.g.

scala> engine.eval("10")
res3: Object = 10

The reason is more or less explained in the gist linked from the FAQ. Basically, when creating an interpreter using getEngineByName("scala"), the java.class.path is used and it contains only sbt-launch.jar. Using the trick with embeddedDefaults sets the class path to the correct value (you can check the settings before and after a call to the embeddedDefaults).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!