Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 462
Harshal Kshatriya Avatar asked Sep 15 '13 12:09

Harshal Kshatriya


People also ask

What is sbt REPL?

You can start the Scala interpreter inside sbt using the console task. The interpreter (also called REPL, for “read-eval-print loop”) is useful for trying out snippets of Scala code. Note that the interpreter can only be started if there are no compilation errors in your code.

What does the scala REPL stand for?

The Scala REPL (“Read-Evaluate-Print-Loop”) is a command-line interpreter that you use as a “playground” area to test your Scala code.

How do I get Scala prompt?

To run Scala from the command-line, download the binaries and unpack the archive. Start the Scala interpreter (aka the “REPL”) by launching scala from where it was unarchived. Start the Scala compiler by launching scalac from where it was unarchived.


2 Answers

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._" 
like image 186
Rüdiger Klaehn Avatar answered Oct 11 '22 22:10

Rüdiger Klaehn


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

like image 27
Zoltán Avatar answered Oct 11 '22 20:10

Zoltán