Sean Bollin
Sean Bollin

Reputation: 910

How to eval a string val in Scala?

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")

Upvotes: 0

Views: 503

Answers (2)

som-snytt
som-snytt

Reputation: 39577

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?

Upvotes: 1

om-nom-nom
om-nom-nom

Reputation: 62835

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

Upvotes: 0

Related Questions