Scala : Can't unquote List[scala.collection.immutable.HashMap[String,Double]]

梦想与她 提交于 2019-12-08 10:32:17

问题


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

来源:https://stackoverflow.com/questions/52950730/scala-cant-unquote-listscala-collection-immutable-hashmapstring-double

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!