Scala: How to add Jar files and classes to the REPL Classpath

This is an excerpt from 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.”

Problem

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.

Solution

If you know that you want to use code from a JAR file when you start the REPL session, add the -cp or -classpath argument to your scala command when you start the session. 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 :cp command:

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.

The Scala Cookbook

This tutorial is sponsored by the Scala Cookbook, which I wrote for O’Reilly:

You can find the Scala Cookbook at these locations:

Add new comment

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

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.