Importing .jar files into Scala environment

2019-02-23 15:36发布

问题:

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._?

回答1:

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



回答2:

Still not sure how :cp works but if you execute

scala -classpath "list of jars colon separated" 

then inside the REPL do your imports it should work

import org.json4s._
import org.xyz

However, when you try to use the classes you are likely to be missing transitive dependencies required by json4s and so we come back to the sbt example @ 4lex1v describes, which will handle this. Creating a little project and running sbt console will indeed greatly simplify this.

Seems like the -classpath and :cp are primarily meant to make your code available in the shell and then only if you understand all of the transitive dependencies, or have none.