Scala - Initialize REPL environment

2020-05-28 07:30发布

问题:

-Hi. I'd like to embed Scala REPL with initialized environment into my app. I've looked at IMain class and it seems I could do it via instance of it. The instance is created and then stored into intp public var in process() of ILoop.

How can I bind some names and/or add some imports before process() (e.g. before REPL)?

Following code fails on line 3 because intp is not yet created (=> 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)

Thank you-.

UPDATE: Overriding createInterpreter() unfortunately doesn't work:

    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)

Interpreter is stuck on input (looks like deadlock, happens only with code above):

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>

Thanks dvigal for suggestion.

回答1:

There is a github project called scala-ssh-shell which may do what you want, or at least get you closer.



回答2:

-Hi, sorry I not Scala REPL hacker but i think you can do something like:

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)  
    }
}