Using SBT to Load External Scala Frameworks in the Scala Command Line Interpreter (REPL)

How do you use external Scala frameworks or Java jar files in the Scala Command Line Interpreter (REPL, aka read–eval–print loop)? You use SBT.SBT is the Scala Interactive Build tool. You can use it to build Scala or Java projects and run a complex series of tasks. It does the same thing as Maven. Maven has a bad reputation for being difficult to learn. SBT too is large and complicated. But here we show how to use it to do the simplest task: add external frameworks to your Scala project.Using REPL is obviously the easiest way to write Scala code as you can work through your ideas one line at a time. But you need the frameworks to be in scope in the interpreter in order to do that. Below we show you how to do that with Scala.With Java packages, if you want to import those inside REPL then you can use this command to add them to the classpath inside the Scala REPL session.:cp /home/walker/Documents/gson-2.2.2.jarThat works, but it is sort of awkward. And the command is :cp with some versions of Scala and :path with others. If you use sbt, to have Scala pick up Java jar files, just copy them to the folder project home/lib folder.The Scala folder structure is like this (This is the simplest example. There are more folders, like test and build target.):projectHomesrcmainscalajavalibIn the project home folder you create a build.sbt file like the one shown below. There you tell it what external Scala frameworks you want to load. Copy the Java jar files you need to the lib folder.To illustrate, suppose we want to use the Argonaut Scala JSON and GSON JSON Java JSON frameworks. We down the GSON JSON as a jar file. But the Scala code we let sbt download.Here is the build.sbt:val argonaut = "io.argonaut" %% "argonaut" % "6.1"lazy val root = (project in file(".")).settings(name := "jsonExample",libraryDependencies += argonaut)This syntax is Scala syntax. Without explaining what each item means in detail, here you can see we have given a name to our project and told it with the libraryDependencies directory to download and compile argonaut. Then if you go the argonaut web site, the installation instructions gives you the syntax to do that:io.argonaut" %% "argonaut" % "6.1"Then SBT will download the argonaut source code from github and include it with your project.Then we run this command to download the Scala framework, start REPL, and add the Java jar file to the classpath so that we can use both in the interactive session:sbt consoleThen in REPL we can import these frameworks:import argonaut._, Argonaut._import;Now we can write Scala code to work with these frameworks. Once the code is complete we can either drop it into the projectHome or scala folders when we want to build our project.


quick inquiry

our latest blogs