0

I have scala expression stored in String variable:

val myExpr = "(xml \ \"node\")"

How do I execute this?

s"${myExpr}" 

Right now it only gives me the string contents

What I'm trying to achieve is parsing user string input in the form:

"/some/node/in/xml"

and get that corresponding node in Scala:

(xml \ "node" \ "in" \ "xml")
5
  • 4
    That's generally a bad idea. Commented Jun 4, 2015 at 22:00
  • I have no clue how to get around doing so. Commented Jun 4, 2015 at 22:01
  • 1
    What do you want to achieve with this in the end? I'm confident there's a better task for the job. Commented Jun 4, 2015 at 22:02
  • Made edits to my post to describe what I'm doing. I need to execute user generated xPath expressions. Commented Jun 4, 2015 at 22:05
  • 4
    Then use a Scala XPath library. Don't do this! Commented Jun 4, 2015 at 22:21

2 Answers 2

1

For the REPL, my init includes:

implicit class interpoleter(val sc: StringContext) {def i(args: Any*) = $intp interpret sc.s(args: _*) }

with which

scala> val myExpr = "(xml \\ \"node\")"
myExpr: String = (xml \ "node")

scala> val xml = <x><node/></x>
xml: scala.xml.Elem = <x><node/></x>

scala> i"${myExpr}"
res3: scala.xml.NodeSeq = NodeSeq(<node/>)
res2: scala.tools.nsc.interpreter.IR.Result = Success

because isn't code really just a string, like everything else?

Sign up to request clarification or add additional context in comments.

Comments

0

Probably, there is some more idiomatic way in recent scala versions, but you can use Twitter's Eval for that:

val i: Int = new Eval()("1 + 1") // => 2

2 Comments

Please don't use Eval! We're trying to kill it!
@TravisBrown what's the reasoning behind this? Can you elaborate on this?

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.