Compute command line in Scala from REPL

Is there a way to evaluate an arbitrary string from Scala, as if the same text was entered directly into the Scala REPL? I want to say that I would like to do something like this:

scala> eval("val x = 42") scala> x res2: Int = 42 

Since the Scala REPL takes commands in an eval loop using jline (I guess) and then compiling / interpreting it, there should be a way to send an arbitrary line of text. I am ready to hack the Scala REPL if necessary.

+4
source share
2 answers

No REPL reboot required - just switch to user mode with power, which gives you access to the current scala.tools.nsc.interpreter.IMain as intp :

 scala> :power ** Power User mode enabled - BEEP BOOP SPIZ ** ** :phase has been set to 'typer'. ** ** scala.tools.nsc._ has been imported ** ** global._ and definitions._ also imported ** ** Try :help, vals.<tab>, power.<tab> ** scala> intp.interpret("val x = 42") x: Int = 42 res0: scala.tools.nsc.interpreter.package.IR.Result = Success scala> x res1: Int = 42 

This works with at least 2.9.1.

+12
source

Another option is to use Eval from the Twitter utility:

 val x: Int = new Eval()("1 + 1") 
+2
source

All Articles