chuxterized
chuxterized

Reputation: 11

scala eval function in string form

I'm trying to define a DSL that will dictate how to parse CSVs. I would like to define simple functions to transform values as the values are being extracted from CSV. The DSL will defined in a text file.

For example, if the CSV looks like this:

id,name,amt
1,John Smith,$10.00
2,Bob Uncle,$20.00

I would like to define the following function (and please note that I would like to be able to execute arbitrary code) on the amt column

(x: String) => x.replace("$", "")

Is there a way to evaluate the function above and execute it for each of the amt values?

Upvotes: 0

Views: 1700

Answers (1)

Brian McCutchon
Brian McCutchon

Reputation: 8584

First, please consider that there's probably a better way to do this. For one thing, it seems concerning that your external DSL contains Scala code. Does this really need to be a DSL?

That said, it's possible to evaluate arbitrary Scala using ToolBox:

import scala.reflect.runtime.universe._
import scala.tools.reflect.ToolBox

val code = """(x: String) => x.replace("$", "")"""
val toolbox = runtimeMirror(getClass.getClassLoader).mkToolBox()
val func = toolbox.eval(toolbox.parse(code)).asInstanceOf[String => String]
println(func("$10.50")) // prints "10.50"

Upvotes: 2

Related Questions