Sasgorilla
Sasgorilla

Reputation: 3130

How can I access the last output value in the Scala REPL?

In Ruby, Python, and presumably a bunch of other REPLs, you can refer to the last value with _:

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

How can I do this in the Scala REPL? I'm aware of the . feature of the REPL:

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

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

But this doesn't do what I want. Neither does _, obviously, or I wouldn't be asking:

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

How can I do this? Ammonite answers good too, but would love to do this in the vanilla REPL.

Upvotes: 0

Views: 180

Answers (1)

prayagupadhyay
prayagupadhyay

Reputation: 31232

you can use default variable names (start with resN) provided by REPL, see example below

scala> case class Bar(name: String)
defined class Bar

scala> Bar(name = "American Football")
res0: Bar = Bar(American Football)

you can see Bar instance is provided a variable res0.

scala> res0.name
res1: String = American Football

scala> val myBar = res0
myBar: Bar = Bar(American Football)

Also see - How can I access the last result in Scala REPL?

Just a side note which might be helpful if you want to list variables

When REPL is just started,

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

After defining classes/variables as in example above;

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

Upvotes: 3

Related Questions