0

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.

Sasgorilla
  • 2,403
  • 2
  • 29
  • 56

1 Answers1

3

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)
prayagupa
  • 30,204
  • 14
  • 155
  • 192
  • Great, thank you. This does what I want. Not sure how I missed that other question (didn't come up in Google search). The `$intp` variable does not work in the `sbt console` for some reason (the `res0` works fine) -- anyone know if there's an equivalent? – Sasgorilla Feb 15 '18 at 13:32
  • `$intp` does work with `sbt console` too, because its provided by scala REPL but `$intp` is probably [available after scala 2.10](https://stackoverflow.com/a/14223796/432903). I am using `Scala 2.12.4` and its working fine. Please check this answer https://stackoverflow.com/a/14223796/432903 for lower scala versions it might be just `intp` – prayagupa Feb 15 '18 at 18:40