2.10 的嵌入式 Scala REPL 解释器示例 [英] Embedded Scala REPL Interpreter example for 2.10

查看:49
本文介绍了2.10 的嵌入式 Scala REPL 解释器示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请给出一个代码示例,说明如何以编程方式创建可在 Scala 2.10 中运行的嵌入式 Scala REPL 解释器.(我花了几个小时整理各种代码片段以获得工作解释器后添加了这个问答)

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 various code scraps to get a working interpreter)

推荐答案

Example Repl.scala:

import scala.tools.nsc.interpreter._
import scala.tools.nsc.Settings


object Repl extends App {
  def repl = new ILoop {
    override def loop(): Unit = {
      intp.bind("e", "Double", 2.71828)
      super.loop()
    }
  }

  val settings = new Settings
  settings.Yreplsync.value = true


  //use when launching normally outside SBT
  settings.usejavacp.value = true      

  //an alternative to 'usejavacp' setting, when launching from within SBT
  //settings.embeddedDefaults[Repl.type]

  repl.process(settings)
}

一些注意事项

  • 我选择显示 JLineReader(默认)而不是 SimpleReader 因为它效果更好,可以正确处理箭头键、删除等.JLine 确实添加了一个 jar 依赖项.
  • 该示例展示了如何将值绑定到 repl(上面的变量 e)中.
  • 当我省略 settings.Yreplsync.value = true 时,REPL 挂起且无用.
  • 根据我的测试,如果 usejavacpembeddedDefaults 设置组合在一起,则会导致错误
  • I choose to show the JLineReader (default) rather than SimpleReader because it works much better, correctly handling arrow keys, delete etc. JLine does add an jar dependency.
  • The example shows how to bind values into the repl (variable e above).
  • When I omit settings.Yreplsync.value = true, the REPL hangs and is useless.
  • From my testing, if both usejavacp and embeddedDefaults settings are combined together, an error results

我发现这最容易通过 SBT 进行测试;示例 build.sbt:

I find this easiest to test via SBT; a sample build.sbt:

name := "Repl"

organization := "ExamplesRUs"

scalaVersion := "2.10.2"

libraryDependencies ++= Seq(
 "org.scala-lang" % "scala-compiler" % "2.10.2",
 "org.scala-lang" % "jline" % "2.10.2"
)

SBT 会话示例:

> run-main Repl
[info] Running Repl
Welcome to Scala version 2.10.2 (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_37).
Type in expressions to have them evaluated.
Type :help for more information.
e: Double = 2.71828

scala> 2 * e
res1: Double = 5.43656

scala>

这篇关于2.10 的嵌入式 Scala REPL 解释器示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆