Scala中的动态代码评估

Scala中的动态代码评估

本文介绍了Scala中的动态代码评估的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将代码片段注入scala的最佳方法是什么?类似于javascript和GroovyScriptEngine中的eval之类的东西.我想将规则/计算/公式保留在实际数据处理课程之外.我有将近100多个要执行的公式.对于所有公式,数据流都是相同的.在Scala中执行此操作的最佳方法是什么?公式的数量会随着时间而增加.

What is the best way to inject a snippet of code to scala? something like eval in javascript and GroovyScriptEngine. I want to keep my rules/computations/formulas outside the actual data processing class. I have close to 100+ formulas to be executed. The data flow is same for all only the formulas change. What is the best way to do it in scala? and the number of formulas will grow over time.

推荐答案

您可以为此使用scala-lang API或twitter-eval.这是scala-lang

You could use either scala-lang API for that or twitter-eval. Here is the snippet of a simple use case of 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
  }
}

或使用Twitter:

or with twitter:

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
  }
}

目前我无法对其进行编译,以检查我是否错过了某些内容,但您应该明白这一点.

I am not able to compile it at the moment to check whether I have missed something but you should get the idea.

这篇关于Scala中的动态代码评估的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 21:15