How to use a Maven repository library with SBT

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 18.17, “Using a Maven Repository Library with SBT.”

Problem

When working on a Scala project built with SBT, you want to use a Java library that’s in a Maven repository, but the library doesn’t include information about how to use it with Scala and SBT.

Solution

Translate the Maven groupId, artifactId, and version fields into an SBT libraryDependencies string.

For example, I wanted to use the Java HTMLCleaner project in a Scala/SBT project. The HTMLCleaner website provided the following Maven information, but no SBT information:

<dependency>
    <groupId>net.sourceforge.htmlcleaner</groupId>
    <artifactId>htmlcleaner</artifactId>
    <version>2.2</version>
</dependency>

Fortunately this translates into the following SBT libraryDependencies string:

libraryDependencies += "net.sourceforge.htmlcleaner" % "htmlcleaner" % "2.2"

After adding this line to my build.sbt file, I ran sbt compile, and watched as it downloaded the HTMLCleaner JAR file and dependencies:

[info] downloading http://repo1.maven.org/maven2/net/sourceforge/htmlcleaner/htmlcleaner/2.2/htmlcleaner-2.2.jar ...
[info]  [SUCCESSFUL ] net.sourceforge.htmlcleaner#htmlcleaner;2.2!htmlcleaner.jar
  (864ms)
[info] downloading http://repo1.maven.org/maven2/org/jdom/jdom/1.1/jdom-1.1.jar ...
[info]  [SUCCESSFUL ] org.jdom#jdom;1.1!jdom.jar (514ms)
[info] downloading 
  http://repo1.maven.org/maven2/org/apache/ant/ant/1.7.0/ant-1.7.0.jar ...
[info]  [SUCCESSFUL ] org.apache.ant#ant;1.7.0!ant.jar (1997ms)
[info] downloading http://repo1.maven.org/maven2/org/apache/ant/ant-launcher/1.7.0/ant-launcher-1.7.0.jar ...
[info]  [SUCCESSFUL ] org.apache.ant#ant-launcher;1.7.0!ant-launcher.jar (152ms)
[info] Done updating.
[info] Compiling 1 Scala source to target/scala-2.10.0/classes...
[success] Total time: 13 s, completed Aug 10, 2012 9:22:38 PM

The libraryDependencies format

As shown in Recipe 18.4, “Managing Dependencies with SBT,” there are two formats for adding a libraryDependencies line to a build.sbt file. The first syntax was used in the Solution, and its general format looks like this:

libraryDependencies += groupID % artifactID % revision

As shown with the HTMLCleaner example, the groupID, artifactID, and revision fields correspond directly to the information you’ll find in the documentation for a Maven library.

The second libraryDependencies form lets you add an optional configuration parameter:

libraryDependencies += groupID % artifactID % revision % configuration

Maven doesn’t use the term configuration, instead using a <scope> tag for the same information. This field is optional, and is typically used for testing libraries such as ScalaTest and specs2, so when it’s needed, the value is usually just test.

See Also