This is an excerpt from the 1st Edition of the Scala Cookbook (partially modified for the internet). This is a short recipe, Recipe 14.3, “How to add Jar files and classes to the Scala REPL Classpath.”
You want to add individual classes or one or more JAR files to the REPL classpath so you can use them in a Scala REPL session.
If you know that you want to use code from a JAR file when you start the REPL session, add the
-classpath argument to your
scala command when you start the session (i.e., at the REPL startup time). This example shows how to load and use my DateUtils.jar library:
$ scala -cp DateUtils.jar scala> import com.alvinalexander.dateutils._ import com.alvinalexander.dateutils._ scala> DateUtils.getCurrentDate res0: String = Saturday, March 16
If you realize you need a JAR file on your classpath after you’ve started a REPL session, you can add one dynamically with the
scala> :cp DateUtils.jar Added '/Users/Al/Projects/Scala/Tests/DateUtils.jar'. Your new classpath is: ".:/Users/Al/Projects/Scala/Tests/DateUtils.jar" scala> import com.alvinalexander.dateutils._ import com.alvinalexander.dateutils._ scala> DateUtils.getCurrentDate res0: String = Saturday, March 16
Compiled class files in the current directory (*.class) are automatically loaded into the REPL environment, so if a simple Person.class file is in the current directory when you start the REPL, you can create a new
Person instance without requiring a classpath command:
scala> val p = new Person("Bill") p: Person = Person(Bill)
However, if your class files are in a subdirectory, you can add them to the environment when you start the session, just as with JAR files. If all the class files are located in a subdirectory named classes, you can include them by starting your REPL session like this:
$ scala -cp classes
If the class files you want to include are in several different directories, you can add them all to your classpath:
$ scala -cp "../Project1/bin:../Project2/classes"
(This command works on Unix systems, but it may be slightly different on Windows.)
These approaches let you add JAR files and other compiled classes to your REPL environment, either at startup or as the REPL is running.