How to run Scala code block using from variable

Hi Guys,

I have requirement , i need to place Scala code in variable , then i need to run that code
Any idea how to execute or if any example plz provide me.
Ex:
val code=" val json_df=sparkSession.read.json(“abc.json”)
json_df.printSchema()
json_df.show()"

i need to run above code using “code” variable

Short answer reflection.
Longer answer, in this case you need to run a full compiler, there is something called scala tool box than can help.

Even longer answer, don’t do this unless you are 100% this is the correct decision.
99% of the time I have some someone wanting to do this, was because they had a design error.

1 Like

Strong agreement – this is almost always a Really Bad Idea. (Not least, it’s a fine recipe for horrible security problems unless you are extremely expert in that topic.)

What’s the actual problem you’re trying to solve? There are usually better approaches than this…

1 Like
scala 2.13.3> val engine = new javax.script.ScriptEngineManager().getEngineByName("scala")
val engine: javax.script.ScriptEngine = scala.tools.nsc.interpreter.shell.Scripted@423692e1

scala 2.13.3> val result = engine.eval("LazyList.from(1).take(5).sum")
val result: Object = 15

scala 2.13.3> result.asInstanceOf[Int]
val res0: Int = 15