2012-09-27 90 views
6

-Hi。我想嵌入Scala REPL 初始化环境到我的应用程序。我看过IMain类,看来我可以通过它的实例来完成它。创建该实例,然后将其存储到intp公共变量process()ILoop中。Scala - 初始化REPL环境

如何在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

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

+0

我看着这个项目,它似乎会工作。谢谢。 – woky

1

嗨,对不起,我不斯卡拉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) 
    } 
} 
+0

不错,谢谢你,不幸的是,它不工作,我已经更新了答案 – woky