请提供一个代码示例,说明如何以编程方式创建嵌入式Scala REPL解释器,该解释器适用于Scala 2.10。 (我花了几个小时梳理各种代码片段以获得一名有效的口译员后,我添加了这个Q& A)
答案 0 :(得分:23)
示例Repl.scala
:
import scala.tools.nsc.interpreter._
import scala.tools.nsc.Settings
object Repl extends App {
def repl = new ILoop {
override def loop(): Unit = {
intp.bind("e", "Double", 2.71828)
super.loop()
}
}
val settings = new Settings
settings.Yreplsync.value = true
//use when launching normally outside SBT
settings.usejavacp.value = true
//an alternative to 'usejavacp' setting, when launching from within SBT
//settings.embeddedDefaults[Repl.type]
repl.process(settings)
}
一些注释
SimpleReader
,因为它工作得更好,正确处理箭头键,删除等.JLine确实添加了jar依赖。e
)。settings.Yreplsync.value = true
时,REPL挂起并且没用。usejavacp
和embeddedDefaults
设置组合在一起,则会出现错误结果我觉得最容易通过SBT进行测试;样本build.sbt
:
name := "Repl"
organization := "ExamplesRUs"
scalaVersion := "2.10.2"
libraryDependencies ++= Seq(
"org.scala-lang" % "scala-compiler" % "2.10.2",
"org.scala-lang" % "jline" % "2.10.2"
)
样本SBT会话:
> run-main Repl
[info] Running Repl
Welcome to Scala version 2.10.2 (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_37).
Type in expressions to have them evaluated.
Type :help for more information.
e: Double = 2.71828
scala> 2 * e
res1: Double = 5.43656
scala>
答案 1 :(得分:4)
基于Ben的优秀答案,下面是一个帮助类来轻松启动解释器。用法:
Repl.run(("e", "Double", 2.71828), ("pi", "Double", 3.1415))
它会自动检测您何时从SBT运行并适应。
Repl.scala:
import scala.tools.nsc.interpreter.ILoop
import scala.tools.nsc.Settings
import java.io.CharArrayWriter
import java.io.PrintWriter
object Repl {
def run(params: (String, String, Any)*) {
def repl = new ILoop {
override def loop(): Unit = {
params.foreach(p => intp.bind(p._1, p._2, p._3))
super.loop()
}
}
val settings = new Settings
settings.Yreplsync.value = true
// Different settings needed when running from SBT or normally
if (isRunFromSBT) {
settings.embeddedDefaults[Repl.type]
} else {
settings.usejavacp.value = true
}
repl.process(settings)
}
def isRunFromSBT = {
val c = new CharArrayWriter()
new Exception().printStackTrace(new PrintWriter(c))
c.toString().contains("at sbt.")
}
}