REPL
The repl
command starts a Scala REPL, which lets you interactively run your code and inspect its results:
scala-cli repl
scala> println("Hello Scala")
Hello Scala
scala> :exit
Scala CLI by default uses the normal Scala REPL.
If you prefer to use the Ammonite REPL, specify --amm
to launch it rather than the default REPL:
Using the Ammonite REPL is restricted and requires setting the --power
option to be used.
You can pass it explicitly or set it globally by running:
scala-cli config power true
scala-cli --power repl --amm
Loading...
Welcome to the Ammonite Repl 2.4.0-23-76673f7f (Scala 3.0.2 Java 11.0.11)
@ println("Hello ammonite")
Hello ammonite
@ exit
Bye!
The repl
command accepts the same arguments as the compile command. It first compiles any provided sources, and then exposes those results and any provided dependencies to the REPL session:
package mylibrary
object Messages {
def message = "Hello"
def print(): Unit = println(message)
}
scala-cli repl mylibrary/Messages.scala
Compiling project (Scala 3.0.2, JVM)
Compiled project (Scala 3.0.2, JVM)
scala> import mylibrary._
scala> Messages.print()
Hello
scala> :quit
Passing REPL options
It is also possible to manually pass REPL-specific options. It can be done in a couple ways:
- after the
--
separator, as the REPL itself is the launched app, so its options are app arguments
scala repl -S 3.6.4-RC1 -- --repl-init-script 'println("Hello")'
Hello
Welcome to Scala 3.6.4-RC1 (23.0.1, Java OpenJDK 64-Bit Server VM).
Type in expressions for evaluation. Or try :help.
scala>
- with the
-O
, effectively passing them as compiler options:
scala repl -S 3.6.4-RC1 -O --repl-init-script -O 'println("Hello")'
Hello
Welcome to Scala 3.6.4-RC1 (23.0.1, Java OpenJDK 64-Bit Server VM).
Type in expressions for evaluation. Or try :help.
scala>
- directly, as a Scala CLI option (do note that newly added options from an RC version or a snapshot may not be supported this way just yet):
scala repl -S 3.6.4-RC1 --repl-init-script 'println("Hello")'
Hello
Welcome to Scala 3.6.4-RC1 (23.0.1, Java OpenJDK 64-Bit Server VM).
Type in expressions for evaluation. Or try :help.
scala>
Using Toolkit in REPL
It is also possible to start the scala-cli REPL with toolkit enabled
scala-cli repl --toolkit default
Welcome to Scala 3.3.1 (17, Java OpenJDK 64-Bit Server VM).
Type in expressions for evaluation. Or try :help.
scala> import os._
scala> os.pwd
val res0: os.Path = /Users/yadukrishnan/test
scala> :quit
Since we started the repl with toolkit enabled, we can use the libraries included in the toolkit directly. In the above example, the os-lib
library from the toolkit is used to print the current path.
Inject code as JAR file in class path
If your application inspects its class path, and requires only JAR files in it, use --as-jar
to
put the Scala CLI project in the class path as a JAR file rather than as a directory:
scala-cli repl Foo.scala --as-jar