|
| 1 | +--- |
| 2 | +layout: overview-large |
| 3 | +title: Programmatic Use of Scala REPL |
| 4 | + |
| 5 | +disqus: true |
| 6 | + |
| 7 | +partof: repl |
| 8 | +num: 2 |
| 9 | +outof: 2 |
| 10 | +--- |
| 11 | + |
| 12 | +The REPL can be embedded and invoked programmatically. |
| 13 | + |
| 14 | +It supports the `javax.script` API, or it can be used |
| 15 | +as either a code interpreter or an interactive command line. |
| 16 | + |
| 17 | + import scala.tools.nsc.Settings |
| 18 | + import scala.tools.nsc.interpreter._ |
| 19 | + import javax.script._ |
| 20 | + |
| 21 | + /** A simple example showing programmatic usage of the REPL. */ |
| 22 | + object Main extends App { |
| 23 | + |
| 24 | + // the REPL has some support for javax.script |
| 25 | + val scripter = new ScriptEngineManager().getEngineByName("scala") |
| 26 | + scripter.eval("""println("hello, world")""") |
| 27 | + |
| 28 | + // compiler settings |
| 29 | + val settings = new Settings |
| 30 | + settings.processArgumentString("-deprecation -feature -Xfatal-warnings -Xlint") |
| 31 | + |
| 32 | + // the interpreter is used by the javax.script engine |
| 33 | + val intp = new IMain(settings) |
| 34 | + def interpret(code: String): Unit = { |
| 35 | + import Results._ |
| 36 | + val res = intp.interpret(code) match { |
| 37 | + case Success => "OK!" |
| 38 | + case _ => "Sorry, try again." |
| 39 | + } |
| 40 | + println(res) |
| 41 | + } |
| 42 | + interpret("""println("hello, world")""") |
| 43 | + interpret("""println(""") |
| 44 | + interpret("""val who = "world" ; println("hello, $who")""") |
| 45 | + |
| 46 | + // the REPL uses a line reader and an interpreter interactively |
| 47 | + val interactive = new ILoop() |
| 48 | + interactive.process(settings) |
| 49 | + |
| 50 | + // input to the REPL can be provided programmatically |
| 51 | + import java.io.{BufferedReader, StringReader, PrintWriter} |
| 52 | + val reader = new BufferedReader(new StringReader(""""hello, world"""")) |
| 53 | + val canned = new ILoop(reader, new PrintWriter(Console.out, true)) |
| 54 | + canned.process(settings) |
| 55 | + |
| 56 | + // more canning |
| 57 | + val code = """println("hello, world") ; 42""" |
| 58 | + val out = ILoop.run(code) |
| 59 | + println(s"Output is $out") |
| 60 | + } |
| 61 | + |
0 commit comments