【问题标题】:How can I access the last output value in the Scala REPL?如何访问 Scala REPL 中的最后一个输出值?
【发布时间】:2018-07-25 18:34:39
【问题描述】:

在 Ruby、Python 以及可能的其他一些 REPL 中,您可以使用 _ 引用最后一个值:

>> longCalculationIForgotToAssignToAVariable
42
>> foo = _
>> foo
42

如何在 Scala REPL 中执行此操作?我知道 REPL 的 . 功能:

scala> foo.getBar()
res1: com.stackoverflow.Bar = [Bar]

scala> .getBaz() // calls method on bar

但这不符合我的要求。 _ 也没有,显然,否则我不会问:

scala> val foo = _
<console>:37: error: unbound placeholder parameter

我该怎么做? Ammonite 的回答也很好,但很想在原版 REPL 中这样做。

【问题讨论】:

    标签: scala read-eval-print-loop ammonite


    【解决方案1】:

    您可以使用 REPL 提供的默认变量名(以 resN 开头),请参见下面的示例

    scala> case class Bar(name: String)
    defined class Bar
    
    scala> Bar(name = "American Football")
    res0: Bar = Bar(American Football)
    

    您可以看到 Bar 实例提供了一个变量 res0

    scala> res0.name
    res1: String = American Football
    
    scala> val myBar = res0
    myBar: Bar = Bar(American Football)
    

    另见 - How can I access the last result in Scala REPL?

    如果您想列出变量,这可能会有所帮助

    REPL刚启动时,

    scala> $intp.unqualifiedIds
    res0: List[String] = List($intp)
    

    如上例定义类/变量后;

    scala> $intp.unqualifiedIds
    res3: List[String] = List($intp, Bar, Bar, myBar, res0, res1, res2)
    

    【讨论】:

    • 太好了,谢谢。这就是我想要的。不知道我是如何错过其他问题的(没有出现在 Google 搜索中)。 $intp 变量由于某种原因在 sbt console 中不起作用(res0 可以正常工作)——有人知道是否有等价物吗?
    • $intp 也适用于 sbt console,因为它由 scala REPL 提供,但 $intp 可能是 available after scala 2.10。我正在使用Scala 2.12.4,它工作正常。请检查此答案 stackoverflow.com/a/14223796/432903 以获取较低的 scala 版本,它可能只是 intp
    猜你喜欢
    • 2012-08-11
    • 2011-10-09
    • 2010-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多