我试图实现一个类来评估给定的scala脚本和输入值的结果,并使用scala.tools.nsc.interpreter.IMain打印评估结果。这是我的测试代码。
package some.test.package
import javax.script.{Compilable, CompiledScript}
import scala.tools.nsc.Settings
import scala.tools.nsc.interpreter.{IMain, JPrintWriter}
class Evaluator {
// Create IMain instance when created
val settings = new Settings()
settings.usejavacp.value = true
val writer = new JPrintWriter(Console.out, true)
val engine = new IMain(settings, writer)
val compiler = engine.asInstanceOf[Compilable]
var inputVal : Int = _
var compiledObj : CompiledScript = _
// compile given script
def compileScript(givenCode : String) {
compiledObj = compiler.compile(givenCode)
}
// evaluate
def evalCompiled(): Unit = {
compiledObj.eval()
}
// set input value
def setInput(givenInput:Int) {
inputVal = givenInput
}
// bind input variable
def bindInput() {
engine.bind("inputVal", "Int", inputVal)
}
}
object IMainTest {
def main(args:Array[String]): Unit = {
// create an instance
val evaluator = new Evaluator()
// first set input value to 3 and do evaluation
evaluator.setInput(3)
evaluator.bindInput()
evaluator.compileScript("def f(x:Int):Int=x+1; println(f(inputVal))")
evaluator.evalCompiled()
// let's change input value and re-evaluate
evaluator.setInput(5)
evaluator.evalCompiled()
}
}
我的期望是节目打印出来' 4'和' 6'但结果却是' 4'和' 4'打印出来。
所以,我的问题是......
我认为很难找到与IMain相关的示例或文档,因此任何参考链接对我来说也可能非常有帮助。谢谢。