从 REPL 评估 Scala 中的字符串命令 [英] Evaluate string command in Scala from REPL

查看:34
本文介绍了从 REPL 评估 Scala 中的字符串命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法像直接将相同的文本输入 Scala REPL 一样评估来自 Scala 的任意字符串?我的意思是,我想做这样的事情:

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

由于 Scala REPL 使用 jline(我相信)在 eval 循环中接受命令,然后编译/解释它,因此必须有一种方法可以提交任意行文本.如有必要,我愿意破解 Scala REPL.

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.

推荐答案

无需 REPL hacking — 只需切换到高级用户模式,即可访问当前的 scala.tools.nsc.interpreter.IMaina> as intp:

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

这至少从 2.9.1 开始有效.

This works since at least 2.9.1.

这篇关于从 REPL 评估 Scala 中的字符串命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆