在任意 Scala 代码位置期间放入解释器 [英] Drop into interpreter during arbitrary scala code location

查看:18
本文介绍了在任意 Scala 代码位置期间放入解释器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我来自 Python 背景,我可以在代码中的任何位置添加

I come from a Python background, where at any point in my code I can add

import pdb; pdb.set_trace()

并且在运行时,我会在那个位置进入交互式解释器.scala 是否有等价物,或者这在运行时是不可能的?

and at runtime I'll be dropped into an interactive interpreter at that spot. Is there an equivalent for scala, or is this not possible at runtime?

推荐答案

是的,你可以,在 Scala 2.8 上.请注意,要使其正常工作,您必须在类路径中包含 scala-compiler.jar.如果你用 scala 调用你的 scala 程序,它会自动完成(或者在我做的测试中看起来是这样).

Yes, you can, on Scala 2.8. Note that, for this to work, you have to include the scala-compiler.jar in your classpath. If you invoke your scala program with scala, it will be done automatically (or so it seems in the tests I made).

然后您可以像这样使用它:

You can then use it like this:

import scala.tools.nsc.Interpreter._

object TestDebugger {
  def main(args: Array[String]) {
    0 to 10 foreach { i =>
      breakIf(i == 5, DebugParam("i", i))
      println(i)
    }
  }
}

您可以传递多个 DebugParam 参数.当 REPL 出现时,右侧的值将绑定到您在左侧提供的名称的 val.例如,如果我像这样更改该行:

You may pass multiple DebugParam arguments. When the REPL comes up, the value on the right will be bound to a val whose name you provided on the left. For instance, if I change that line like this:

      breakIf(i == 5, DebugParam("j", i))

然后执行会像这样:

C:UsersDanielDocumentsScalaProgramas>scala TestDebugger
0
1
2
3
4
j: Int

scala> j
res0: Int = 5

输入 :quit 继续执行.

您也可以通过调用 break 无条件地进入 REPL,它接收 DebugParamList 而不是 vararg.这是一个完整的示例、代码和执行:

You may also unconditionally drop into REPL by invoking break, which receives a List of DebugParam instead of a vararg. Here's a full example, code and execution:

import scala.tools.nsc.Interpreter._

object TestDebugger {
  def main(args: Array[String]) {
    0 to 10 foreach { i =>
      breakIf(i == 5, DebugParam("j", i))
      println(i)
      if (i == 7) break(Nil)
    }
  }
}

然后:

C:UsersDanielDocumentsScalaProgramas>scalac TestDebugger.scala

C:UsersDanielDocumentsScalaProgramas>scala TestDebugger
0
1
2
3
4
j: Int

scala> j
res0: Int = 5

scala> :quit
5
6
7

scala> j
<console>:5: error: not found: value j
       j
       ^

scala> :quit
8
9
10

C:UsersDanielDocumentsScalaProgramas>

这篇关于在任意 Scala 代码位置期间放入解释器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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