6

-你好。我想将带有初始化环境的 Scala REPL 嵌入到我的应用程序中。我看过IMain课程,似乎我可以通过它的实例来做到这一点。创建实例,然后将其存储到intppublic var in process()of 中ILoop

如何在之前绑定一些名称和/或添加一些导入process()(例如在 REPL 之前)?

以下代码在第 3 行失败,因为intp尚未创建(=> NPE):

    val x = 3
    val interp = new ILoop
    interp.bind("x", x) // -> interp.intp.bind("x", x)
    val settings = new Settings
    settings.usejavacp.value = true
    interp.process(settings)

谢谢-。

更新:不幸的是,重写createInterpreter()不起作用:

    val x = 3
    val interp = new ILoop {
        override def createInterpreter() {
            super.createInterpreter()
            intp.bind("x", x) // -> interp.intp.bind("x", x)
        }
    }
    val settings = new Settings
    settings.usejavacp.value = true
    interp.process(settings)

解释器卡在输入上(看起来像死锁,只发生在上面的代码中):

x: Int = 3
Failed to created JLineReader: java.lang.NoClassDefFoundError: scala/tools/jline/console/completer/Completer
Falling back to SimpleReader.
Welcome to Scala version 2.9.2 (OpenJDK 64-Bit Server VM, Java 1.7.0_06-icedtea).
Type in expressions to have them evaluated.
Type :help for more information.

scala> println
<infinite_sleep>

感谢 dvigal 的建议。

4

2 回答 2

4

有一个名为scala-ssh-shell的 github 项目可以做你想做的事,或者至少让你更接近。

于 2012-09-28T23:08:25.790 回答
1

-嗨,对不起,我不是 Scala REPL 黑客,但我认为您可以执行以下操作:

class YourILoop(in0: Option[BufferedReader], protected override val out: JPrintWriter)         
    extends ILoop(in0, out) {
    override def createInterpreter() {
       if (addedClasspath != "")
          settings.classpath append addedClasspath

          intp = new ILoopInterpreter
          val x = 3;
          intp.bind("x", x)
    }
}
object Run {
    def errorFn(str: String): Boolean = {
      Console.err println str
      false
    }

    def process(args: Array[String]): Boolean = {
        val command = new GenericRunnerCommand(args.toList, (x: String) => errorFn(x))
        import command.{ settings, howToRun, thingToRun }
        new YourILoop process settings
    }
    def main(args: Array[String]) {
        process(args)  
    }
}
于 2012-09-28T03:52:19.140 回答