在任意scala代码位置下降到解释器 [英] Drop into interpreter during arbitrary scala code location
问题描述
我来自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).
然后可以这样使用:
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:\Users\Daniel\Documents\Scala\Programas>scala TestDebugger
0
1
2
3
4
j: Int
scala> j
res0: Int = 5
您可以通过键入:退出
。
您也可以通过调用 break
无条件放入REPL中,它收到列表
DebugParam
而不是一个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:\Users\Daniel\Documents\Scala\Programas>scalac TestDebugger.scala
C:\Users\Daniel\Documents\Scala\Programas>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:\Users\Daniel\Documents\Scala\Programas>
这篇关于在任意scala代码位置下降到解释器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!