Importing .jar files into Scala environment

Alex Spangher picture Alex Spangher · Jul 2, 2013 · Viewed 13k times · Source

Even after reading: Scala, problem with a jar file, I'm still a bit confused. I am trying to import some packages into my Scala file, and the interpreter is not recognizing them even after adding to classpath.

One example:

I have the import statement:

import org.json4s._

I downloaded the .jar from here: http://mvnrepository.com/artifact/org.json4s/json4s-native_2.10/3.2.4

and added to the interpreter classpath using:

scala> :cp /Users/aspangher13/Downloads/json4s-native_2.10-3.2.4.jar

Scala acknowledges the classpath:

Your new classpath is: ".:/Users/aspangher13/Downloads/json4s-native_2.10-3.2.4.jar:/Users/aspangher13/Downloads/jna-3.5.2.jar"

But still throws this error:

<console>:7: error: object scalatra is not a member of package org
   import org.json4s._

Can anyone see what I'm doing wrong? Thanks!!

And as a followup, does anyone know where to find the package: JsonAST._?

Answer

4lex1v picture 4lex1v · Jul 2, 2013

Go the simple and create a little sbt project.

First step - create a project

For your purposes you don't need a complex build. So just create two files:

./build.sbt

name := "name your project"

version := "0.1"

scalaVersion := "2.10.2" // or whatever you prefer

./project/build.properties

sbt.version=0.12.4

The just go to the project root folder and call sbt

Second step - add dependencies

Open your ./build.sbt file and add:

libraryDependency ++= Seq(
  "org.scalatra" %% "scalatra" % "2.2.1",
  "org.scalatra" %% "scalatra-scalate" % "2.2.1",
  "org.scalatra" %% "scalatra-specs2" % "2.2.1" % "test",
  "org.json4s"   %% "json4s-native % "3.2.4",
  "net.java.dev.jna" & "jna" & "3.5.2"
)

Step three - run the console

Don't forget to reload sbt with reload task, and then call console or console-quick task. This should work.

But there are easier ways to do this:

1) Use gitter8 - Scalatra gitter8 project
2) Read little into about Scalatra sbt dependencies