Is it possible to create (enter) nested environments in Scala REPL, such that after exiting the nested environment, all variable bindings created within the exited environment will be lost?
Here is what I wish a session could look like:
scala> val x = 1
x: Int = 1
scala> enter // How to implement this?
// Entering nested context (type exit to exit)
scala> val x = 2
x: Int = 2
scala> val y = 3
y: Int = 3
scala> exit // How to implement this?
// Exiting nested context
scala> assert(x == 1)
scala> y
<console>:12: error: not found: value y
y
^
scala>
This isn't possible with the current Scala REPL, but you can achieve something similar using the Ammonite REPL:
These sessions aren't nested exactly the way you describe, but are easy to track by name, and can overlap. That is after
repl.sess.save("first")
, you still have access to the originalx
if you don't override it.After playing around with it some more, I was able to concoct a simple object that uses a stack to track the sessions and load/save them. It can be placed in
~/.ammonite/predef.sc
to load automatically with the Ammonite REPL:I haven't tested this rigorously, so there may be an edge-case that isn't covered, but I was able to go a few levels deep easily and then peel back the layers.