Evaluate string command in Scala from REPL

北慕城南 提交于 2019-12-19 09:01:02

问题


Is there a way to evaluate a arbitrary string from Scala as if the same text was entered into the Scala REPL directly? I mean, I would like to do something like this:

scala> eval("val x = 42")

scala> x
res2: Int = 42

Since the Scala REPL is accepting commands in an eval loop using jline (I believe) and then compiling/interpreting it, there has to be a way to submit an arbitrary line of text. I am willing to hack the Scala REPL if necessary.


回答1:


No REPL hacking necessary—just switch to power user mode, which gives you access to the current scala.tools.nsc.interpreter.IMain as intp:

scala> :power
** Power User mode enabled - BEEP BOOP SPIZ **
** :phase has been set to 'typer'.          **
** scala.tools.nsc._ has been imported      **
** global._ and definitions._ also imported **
** Try  :help,  vals.<tab>,  power.<tab>    **

scala> intp.interpret("val x = 42")
x: Int = 42
res0: scala.tools.nsc.interpreter.package.IR.Result = Success

scala> x
res1: Int = 42

This works since at least 2.9.1.




回答2:


Another opportunity is to use Eval from Twitter Utility:

val x: Int = new Eval()("1 + 1")


来源:https://stackoverflow.com/questions/11923378/evaluate-string-command-in-scala-from-repl

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