有没有办法评估 Scala 中的任意字符串,就好像直接将相同的文本输入到 Scala REPL 中一样?我的意思是,我想做这样的事情:
scala> eval("val x = 42")
scala> x
res2: Int = 42
由于 Scala REPL 使用 jline (我相信)在 eval 循环中接受命令,然后编译/解释它,因此必须有一种方法来提交任意文本行。如有必要,我愿意破解 Scala REPL。
无需 REPL 黑客攻击 - 只需切换到高级用户模式,即可访问当前的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
这至少从 2.9.1 开始有效。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)