2012-09-27 84 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