How to use third party libraries with Scala REPL?
I've downloaded Algebird and I want to try out few things in the Scala interpreter using this library. How do I achieve this?
Solution 1:
Of course, you can use scala -cp whatever and manually manage your dependencies. But that gets quite tedious, especially if you have multiple dependencies.
A more flexible approach is to use sbt to manage your dependencies. Search for the library you want to use on search.maven.org. Algebird for example is available by simply searching for algebird. Then create a build.sbt referring to that library, enter the directory and enter sbt console. It will download all your dependencies and start a scala console session with all dependencies automatically on the classpath.
Changing things like the scala version or the library version is just a simple change in the build.sbt. To play around you don't need any scala code in your directory. An empty directory with just the build.sbt will do just fine.
Here is a build.sbt for using algebird:
name := "Scala Playground"
version := "1.0"
scalaVersion := "2.10.2"
libraryDependencies += "com.twitter" % "algebird-core" % "0.2.0"
Edit: often when you want to play around with a library, the first thing you have to do is to import the namespace(s) of the library. This can also be automated in the build.sbt by adding the following line:
initialCommands in console += "import com.twitter.algebird._"
Solution 2:
Running sbt console
will not import libraries declared with a test scope. To use those libraries in the REPL, start the console with
sbt test:consoleQuick
You should be aware, however, that starting the console this way skips compiling your test sources.
Source: http://www.scala-sbt.org/0.13/docs/Howto-Scala.html
Solution 3:
You can use the scala's -cp
switch to keep jars on the classpath. There are other switches available too, for example, -deprecation
and -unchecked
for turning on various warnings. Many more to be found with scala -X...
and scala -Y...
. You can find out more information about these switches with scala -help