Embedded Scala REPL Interpreter example for 2.10

前端 未结 2 984
南方客
南方客 2021-02-04 04:05

Please give a code example of how to create an embedded Scala REPL interpreter programmatically, that works in Scala 2.10. (I added this Q&A after spending hours combing

2条回答
  •  暖寄归人
    2021-02-04 04:25

    Based on Ben's excellent answer, below is a helper class to ease starting the interpreter. Usage:

    Repl.run(("e", "Double", 2.71828), ("pi", "Double", 3.1415))
    

    It automatically detects when you're running from SBT and accommodates.

    Repl.scala:

    import scala.tools.nsc.interpreter.ILoop
    import scala.tools.nsc.Settings
    import java.io.CharArrayWriter
    import java.io.PrintWriter
    
    object Repl {
    
      def run(params: (String, String, Any)*) {
    
        def repl = new ILoop {
          override def loop(): Unit = {
            params.foreach(p => intp.bind(p._1, p._2, p._3))
            super.loop()
          }
        }
    
        val settings = new Settings
        settings.Yreplsync.value = true
    
        // Different settings needed when running from SBT or normally
        if (isRunFromSBT) {
          settings.embeddedDefaults[Repl.type]
        } else {
          settings.usejavacp.value = true
        }
    
        repl.process(settings)
      }
    
      def isRunFromSBT = {
        val c = new CharArrayWriter()
        new Exception().printStackTrace(new PrintWriter(c))
        c.toString().contains("at sbt.")
      }
    
    }
    

提交回复
热议问题