使用 Scala Toolbox eval,我如何定义我可以在以后的 eval 中使用的值?
Using Scala Toolbox eval, how do I define I value I can use in later evals?
我正在使用 Scala 工具箱为 Web 解释器评估一些 Scala 代码。它运行良好,代码如下所示:
import scala.reflect.runtime.universe._
import scala.tools.reflect.ToolBox
object Eval {
val toolbox = runtimeMirror(getClass.getClassLoader).mkToolBox()
def eval[T](code: String): T = {
toolbox.eval(toolbox.parse(code)).asInstanceOf[T]
}
}
我可以这样做:
Eval.eval[Long]("1 + 1")
然后 2
回来。当我想定义一些东西时出现了这个问题:
Eval.eval[Unit]("val yellow = 5")
Eval.eval[Long]("yellow")
我收到 not found: value yellow
错误。如何定义可在以后使用 Scala Toolbox 进行评估时使用的值?
对于持久化环境,可以直接使用Scala的REPL。请参阅 2.11 release notes.
最底部的 JSR-223 说明
import javax.script.ScriptEngineManager
class DummyClass
object Evaluator {
val engine = new ScriptEngineManager().getEngineByName("scala")
val settings = engine.asInstanceOf[scala.tools.nsc.interpreter.IMain].settings
settings.embeddedDefaults[DummyClass]
engine.eval("val x: Int = 5")
val thing = engine.eval("x + 9").asInstanceOf[Int]
}
对 DummyClass
(或者实际上任何 class 都可以替代 DummyClass
)的需求源于这里发生的一些恶作剧 due to SBT and classloader concerns (more details here)。
我正在使用 Scala 工具箱为 Web 解释器评估一些 Scala 代码。它运行良好,代码如下所示:
import scala.reflect.runtime.universe._
import scala.tools.reflect.ToolBox
object Eval {
val toolbox = runtimeMirror(getClass.getClassLoader).mkToolBox()
def eval[T](code: String): T = {
toolbox.eval(toolbox.parse(code)).asInstanceOf[T]
}
}
我可以这样做:
Eval.eval[Long]("1 + 1")
然后 2
回来。当我想定义一些东西时出现了这个问题:
Eval.eval[Unit]("val yellow = 5")
Eval.eval[Long]("yellow")
我收到 not found: value yellow
错误。如何定义可在以后使用 Scala Toolbox 进行评估时使用的值?
对于持久化环境,可以直接使用Scala的REPL。请参阅 2.11 release notes.
最底部的 JSR-223 说明import javax.script.ScriptEngineManager
class DummyClass
object Evaluator {
val engine = new ScriptEngineManager().getEngineByName("scala")
val settings = engine.asInstanceOf[scala.tools.nsc.interpreter.IMain].settings
settings.embeddedDefaults[DummyClass]
engine.eval("val x: Int = 5")
val thing = engine.eval("x + 9").asInstanceOf[Int]
}
对 DummyClass
(或者实际上任何 class 都可以替代 DummyClass
)的需求源于这里发生的一些恶作剧 due to SBT and classloader concerns (more details here)。