How to add a new jar file to the Scala REPL classpath (interactive command line)

Scala REPL FAQ: How do I add a Jar file to the Scala REPL classpath? (The Scala REPL is the interactive command line you get if you just type "scala" at your command line.)

To add a new jar file to the Scala REPL classpath (interactive command line classpath), use the ":cp" command at the command line, like this:

scala> :cp myjar.jar

After you do this, you should see a reply from the REPL like this:

Added '/Users/Al/tests/myjar.jar'. Your new classpath is: ".:/Users/Al/tests/myjar.jar"

At this time you can begin using the classes in your jar (though you'll have to import them, as usual).

Adding a jar file to the classpath when you start the Scala interpreter

I usually find that I need to add a jar file to the Scala REPL after I've been running the REPL, but if you happen to know that you're going to need to add a jar file to the classpath when you start the interpreter, you can do so like this:

$ scala -cp junit-4.8.1.jar

As you can see, this approach uses the usual "-cp" classpath option that is used by the scalac and javac commands.

Scala REPL help

I learned about the Scala REPL ":cp" command by looking at the "help" from within the REPL. Here's what that help looks like with my current version of Scala, version 2.9.1:

scala> :help
All commands can be abbreviated, e.g. :he instead of :help.
Those marked with a * have more detailed help, e.g. :help imports.

:cp <path>                 add a jar or directory to the classpath
:help [command]            print this summary or command-specific help
:history [num]             show the history (optional num is commands to show)
:h? <string>               search the history
:imports [name name ...]   show import history, identifying sources of names
:implicits [-v]            show the implicits in scope
:javap <path|class>        disassemble a file or class name
:keybindings               show how ctrl-[A-Z] and other keys are bound
:load <path>               load and interpret a Scala file
:paste                     enter paste mode: all input up to ctrl-D compiled together
:power                     enable power user mode
:quit                      exit the interpreter
:replay                    reset execution and replay all previous commands
:sh <command line>         run a shell command (result is implicitly => List[String])
:silent                    disable/enable automatic printing of results
:type <expr>               display the type of an expression without evaluating it

Post new comment

The content of this field is kept private and will not be shown publicly.