【问题标题】:Scala - Initialize REPL environmentScala - 初始化 REPL 环境
【发布时间】:2012-09-19 17:58:20
【问题描述】:

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

如何在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 的建议。

【问题讨论】:

    标签: scala embed bind read-eval-print-loop


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      -嗨,对不起,我不是 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)  
          }
      }
      

      【讨论】:

      • 不错,谢谢,不幸的是它不起作用,我已经更新了答案
      猜你喜欢
      • 2017-07-18
      • 1970-01-01
      • 2012-05-05
      • 2015-08-05
      • 1970-01-01
      • 2013-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多