0

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?

2
  • So your question is how to extract amt only? Commented Jun 17, 2018 at 5:42
  • Please can you check URl stackoverflow.com/help/how-to-ask for enhance quality. Commented Jun 17, 2018 at 5:46

1 Answer 1

2

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"
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @Brian McCutchon I agree that there probably is a better way to do this, but I plan on using this as a building block for other things and to prove a concept. Thanks for your concern and help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.