How to use third party libraries with Scala REPL?
This is an answer using Ammonite (as opposed to the Scala REPL) - but it is such a great tool that it is worth mentioning.
- You can install it with a one liner such as:
sudo sh -c '(echo "#!/usr/bin/env sh" && curl -L https://github.com/lihaoyi/Ammonite/releases/download/2.1.2/2.13-2.1.2) > /usr/local/bin/amm && chmod +x /usr/local/bin/amm' && amm
or using brew on macOS:
brew install ammonite-repl
For scala 2.10, you need to use an oder version 1.0.3:
sudo sh -c '(echo "#!/usr/bin/env sh" && curl -L https://github.com/lihaoyi/Ammonite/releases/download/1.0.3/2.10-1.0.3) > /usr/local/bin/amm && chmod +x /usr/local/bin/amm' && amm
- Run Ammonite in your terminal:
amm
// Displays
Loading...
Welcome to the Ammonite Repl 2.1.0 (Scala 2.12.11 Java 1.8.0_242)
- Use in ivy import to import your 3rd part library:
import $ivy.`com.twitter::algebird-core:0.2.0`
Then you can use your library within the Ammonite-REPL:
import com.twitter.algebird._
import com.twitter.algebird.Operators._
Map(1 -> Max(2)) + Map(1 -> Max(3)) + Map(2 -> Max(4))
...
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
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
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._"