Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluate string command in Scala from REPL

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

scala> eval("val x = 42")

scala> x
res2: Int = 42

Since the Scala REPL is accepting commands in an eval loop using jline (I believe) and then compiling/interpreting it, there has to be a way to submit an arbitrary line of text. I am willing to hack the Scala REPL if necessary.

like image 372
Jim Avatar asked Aug 12 '12 15:08

Jim


People also ask

How does the scala REPL store the results of evaluated expressions?

The REPL reads expressions at the prompt In interactive mode, then wraps them into an executable template, and after that compiles and executes the result. Either an object Or a class can be wrapped by user code the switch used is -Yrepl-class-based. Each and every line of input is compiled separately.

Does scala have REPL?

The Scala REPL is a tool (scala) for evaluating expressions in Scala. The scala command will execute a source script by wrapping it in a template and then compiling and executing the resulting program.

What does the scala REPL stand for?

The Scala REPL (“Read-Evaluate-Print-Loop”) is a command-line interpreter that you use as a “playground” area to test your Scala code.

What is RES in scala?

res in scala shell are val. you can verify this by trying to reassign a value to res. e.g. - scala> List(1)


2 Answers

No REPL hacking necessary—just switch to power user mode, 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 since at least 2.9.1.

like image 137
Travis Brown Avatar answered Sep 27 '22 19:09

Travis Brown


Another opportunity is to use Eval from Twitter Utility:

val x: Int = new Eval()("1 + 1")
like image 20
om-nom-nom Avatar answered Sep 27 '22 19:09

om-nom-nom