I am using Scala reflection and toolbox to evaluate dynamic function as a string.
And I am trying to evaluate it with data of type List[HashMap[String, Double]]
But it is giving error
Can't unquote List[scala.collection.immutable.HashMap[String,Double]], consider
using ...
val dataAfterFunctionApplied = tb.eval(q"$functionSymbol.function($data)")
The code which I am using is as below.
package test
import scala.collection
import scala.collection.immutable.HashMap
import scala.reflect.runtime.universe.{Quasiquote, runtimeMirror}
import scala.tools.reflect.ToolBox
object ReflectionTest {
def main(args: Array[String]): Unit = {
val mirror = runtimeMirror(getClass.getClassLoader)
val tb = ToolBox(mirror).mkToolBox()
val data = List(
HashMap("a" -> 1.0, "b" -> 267.0, "c" -> 26.0, "d" -> 2.0),
HashMap("a" -> 1.0, "b" -> 2678.0, "c" -> 40.0, "d" -> 2.0),
HashMap("a" -> 4.0, "b" -> 267.0, "c" -> 26.0, "d" -> 2.0),
HashMap("a" -> 1.0, "b" -> 2678.0, "c" -> 90.0, "d" -> 17.0)
)
println("Data before function applied on it")
println(data.mkString(","))
val function = "def function(result: List[HashMap[String, Double]])={result.map(x=>(x('a'.toString)+x('b'.toString)))}"
val functionWrapper = "object FunctionWrapper { " + function + "}"
val functionSymbol=tb.define(tb.parse(functionWrapper).asInstanceOf[tb.u.ImplDef])
val dataAfterFunctionApplied = tb.eval(q"$functionSymbol.function($data)")
println("Data after function applied on it")
}
}
If I am using Map
(datatype) instead of HashMap
then it is working, but the time consuming while parsing and evaluation is too much. So, I am trying to do it with HashMap
.
But Unfortunately getting this error.
It is working with Map, that's ok. But the performance issue is coming because of toolbox parsing and evaluation from string to code. Any efficient way to parse string to code in scala??