将一段代码注入(inject)scala的最佳方法是什么?类似于 javascript 和 GroovyScriptEngine 中的 eval 。我想将我的规则/计算/公式保留在实际数据处理类之外。我有将近 100 多个公式要执行。所有的数据流都是相同的,只是公式发生了变化。在scala中最好的方法是什么?并且公式的数量会随着时间的推移而增长。
最佳答案
您可以使用 scala-lang
API 或 twitter-eval
.这是 scala-lang
的简单用例的片段
import scala.tools.nsc.Settings
import scala.tools.nsc.interpreter.IMain
object ScalaReflectEvaluator {
def evaluate() = {
val clazz = prepareClass
val settings = new Settings
settings.usejavacp.value = true
settings.deprecation.value = true
val eval = new IMain(settings)
val evaluated = eval.interpret(clazz)
val res = eval.valueOfTerm("res0").get.asInstanceOf[Int]
println(res) //yields 9
}
private def prepareClass: String = {
s"""
|val x = 4
|val y = 5
|x + y
|""".stripMargin
}
}
或推特:
import com.twitter.util.Eval
object TwitterUtilEvaluator {
def evaluate() = {
val clazz = prepareClass
val eval = new Eval
eval.apply[Int](clazz)
}
private def prepareClass: String = {
s"""
|val x = 4
|val y = 5
|x + y
|""".stripMargin
}
}
我现在无法编译它来检查我是否遗漏了一些东西,但你应该明白了。
关于scala - scala中的动态代码评估,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39142979/