Skip to content

Instantly share code, notes, and snippets.

@tokunbo
Last active January 16, 2017 06:16
Show Gist options
  • Save tokunbo/033c041c7bcd8635c8b2b1676e74f9ef to your computer and use it in GitHub Desktop.
Save tokunbo/033c041c7bcd8635c8b2b1676e74f9ef to your computer and use it in GitHub Desktop.
/*
You'll see all kinds of different programatic scala REPL solutions out there, but for me they all have at least one of the following problems:
- Crash before prompt appears if you previously used repl.intp.bind before starting it.
- Prompt appears but every command crashes
- Works but no access to variables before the REPL started
- Works... but intermittently
....After a bunch of testing, I eventually reached the conclusion that the repl.intp isn't ready yet... so I start a Future
that'll bind the variable 2 seconds after the repl starts. So far this has been the reliable method.
*/
import scala.tools.nsc.interpreter.ILoop
import scala.tools.nsc.Settings
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
def prompt(myvar:Any) = {
val repl = new ILoop
val settings = new Settings
settings.usejavacp.value = true
repl.settings = settings
repl.in = SimpleReader()
repl.createInterpreter()
repl.intp.initializeSynchronous()
val gf = repl.getClass.getDeclaredField("globalFuture")
gf.setAccessible(true)
gf.set(repl, scala.concurrent.Future.successful(true)) //This person says to do this - http://stackoverflow.com/a/28062917
Future {
Thread.sleep(2000)
repl.intp.bind("myvar", "Any", myvar)
}
repl.process(settings)
repl.closeInterpreter()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment