How do I import a Java package in Scala? - scala

I have created a jar-file with a compiled Java class. Now I want to import it in Scala. But it doesn't work.
The package name is se.mydomain.testproj and here is a small Scala application:
object TestCrypt {
import se.mydomain.testproj._
def main(args: Array[String]) {
println("Hello")
}
}
I use Eclipse and have added the jar file to the Build Path.
In Eclipse, I get the error: not found: value se
How can I import Java classes from a Jar file in Scala?

I do this all the time in Eclipse, so it definitely works. Do you see the jar in the Referenced Libraries of the project? Do you have the package name right?
Also, an import in the object as opposed to the top of the file should be fine.

Related

Import code packaged as jar into another sbt project

I want to import below code packaged as jar to another sbt intellij project how could i do this?
package yyy
object Hello extends Greeting with App {
println(greeting)
}
trait Greeting {
lazy val greeting: String = "hello"
}
If you have this code packaged as a jar, you can simply place it in the lib/ folder of the other sbt project. It should be on the classpath, so you'll be able to do import yyy._ in the code.
You can read more about unmanaged dependencies in the sbt documentation. Here's an excerpt from it:
Unmanaged dependencies work like this: add jars to lib and they will be placed on the project classpath. Not much else to it!
Dependencies in lib go on all the classpaths (for compile, test, run, and console).
There’s nothing to add to build.sbt to use unmanaged dependencies, though you could change the unmanagedBase key if you’d like to use a different directory rather than lib.

object scala in compiler mirror not found - running Scala compiler programatically [no sbt - no IDE] [duplicate]

I'm trying to run a Scala application packed as JAR (including dependencies) but this fails until the Scala library is added by using the -Xbootclasspath/p option.
Failing invocation:
java -jar /path/to/target/scala-2.10/application-assembly-1.0.jar
After the application did some of its intended output, the console shows:
Exception in thread "main"
scala.reflect.internal.MissingRequirementError: object scala.runtime
in compiler mirror not found.
at scala.reflect.internal.MissingRequirementError$.signal(MissingRequirementError.scala:16)
at scala.reflect.internal.MissingRequirementError$.notFound(MissingRequirementError.scala:17)
at scala.reflect.internal.Mirrors$RootsBase.getModuleOrClass(Mirrors.scala:48)
at scala.reflect.internal.Mirrors$RootsBase.getModuleOrClass(Mirrors.scala:40)
at scala.reflect.internal.Mirrors$RootsBase.getModuleOrClass(Mirrors.scala:61)
at scala.reflect.internal.Mirrors$RootsBase.getPackage(Mirrors.scala:172)
at scala.reflect.internal.Mirrors$RootsBase.getRequiredPackage(Mirrors.scala:175)
at scala.reflect.internal.Definitions$DefinitionsClass.RuntimePackage$lzycompute(Definitions.scala:181)
at scala.reflect.internal.Definitions$DefinitionsClass.RuntimePackage(Definitions.scala:181)
at scala.reflect.internal.Definitions$DefinitionsClass.RuntimePackageClass$lzycompute(Definitions.scala:182)
at scala.reflect.internal.Definitions$DefinitionsClass.RuntimePackageClass(Definitions.scala:182)
at scala.reflect.internal.Definitions$DefinitionsClass.AnnotationDefaultAttr$lzycompute(Definitions.scala:1015)
at scala.reflect.internal.Definitions$DefinitionsClass.AnnotationDefaultAttr(Definitions.scala:1014)
at scala.reflect.internal.Definitions$DefinitionsClass.syntheticCoreClasses$lzycompute(Definitions.scala:1144)
at scala.reflect.internal.Definitions$DefinitionsClass.syntheticCoreClasses(Definitions.scala:1143)
at scala.reflect.internal.Definitions$DefinitionsClass.symbolsNotPresentInBytecode$lzycompute(Definitions.scala:1187)
at scala.reflect.internal.Definitions$DefinitionsClass.symbolsNotPresentInBytecode(Definitions.scala:1187)
at scala.reflect.internal.Definitions$DefinitionsClass.init(Definitions.scala:1252)
at scala.tools.nsc.Global$Run.(Global.scala:1290)
at extract.ScalaExtractor$Compiler$2$.(ScalaExtractor.scala:24)
Working invocation:
java -Xbootclasspath/p:/path/to/home/.sbt/boot/scala-2.10.2/lib/scala-library.jar -jar /path/to/target/scala-2.10/application-assembly-1.0.jar
The strange thing about it is that the application-assembly-1.0.jar was built so that it includes all dependencies including the Scala library. When one extracts the JAR file it can be verified that the class files in the scala.runtime package have been included.
Creation of the JAR file
addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.9.1") was added to project/plugins.sbt and the assembly target was invoked. A JAR file of about 25MB results.
Building the JAR with proguard shows the same runtime behavior as seen with assembly's JAR file.
Application code that triggers the MissingRequirementError
Some application code works fine and the previously described exception is triggered as soon as the new Run from the following fragment executes.
import scala.reflect.internal.util.BatchSourceFile
import scala.reflect.io.AbstractFile
import scala.reflect.io.Path.jfile2path
import scala.tools.nsc.Global
import scala.tools.nsc.Settings
…
import scala.tools.nsc._
object Compiler extends Global(new Settings()) {
new Run // This is line 24 from the stack trace!
def parse(path: File) = {
val code = AbstractFile.getFile(path)
val bfs = new BatchSourceFile(code, code.toCharArray)
val parser = new syntaxAnalyzer.UnitParser(new CompilationUnit(bfs))
parser.smartParse()
}
}
val ast = Compiler.parse(file)
Among others, scala-library, scala-compiler and scala-reflect are defined as dependencies in build.sbt.
For the curios / background information
The aim of the application is to aid in localization of Java and Scala programs. The task of the code fragment above is to get an AST from a Scala file in order to find method calls in there.
The questions
Given the Scala library is included in the JAR file, why is necessary to call the JAR using -Xbootclasspath/p:scala-library.jar?
Why do other parts of the application run just fine even though scala.runtime is reported as missing later?
The easy way to configure the settings with familiar keystrokes:
import scala.tools.nsc.Global
import scala.tools.nsc.Settings
def main(args: Array[String]) {
val s = new Settings
s processArgumentString "-usejavacp"
val g = new Global(s)
val r = new g.Run
}
That works for your scenario.
Even easier:
java -Dscala.usejavacp=true -jar ./scall.jar
Bonus info, I happened to come across the enabling commit message:
Went ahead and implemented classpaths as described in email to
scala-internals on the theory that at this point I must know what I'm
doing.
** PUBLIC SERVICE ANNOUNCEMENT **
If your code of whatever kind stopped working with this commit (most
likely the error is something like "object scala not found") you can
get it working again with either of:
passing -usejavacp on the command line
set system property "scala.usejavacp" to "true"
Either of these will alert scala that you want the java application
classpath to be utilized by scala as well.

"scala.runtime in compiler mirror not found" but working when started with -Xbootclasspath/p:scala-library.jar

I'm trying to run a Scala application packed as JAR (including dependencies) but this fails until the Scala library is added by using the -Xbootclasspath/p option.
Failing invocation:
java -jar /path/to/target/scala-2.10/application-assembly-1.0.jar
After the application did some of its intended output, the console shows:
Exception in thread "main"
scala.reflect.internal.MissingRequirementError: object scala.runtime
in compiler mirror not found.
at scala.reflect.internal.MissingRequirementError$.signal(MissingRequirementError.scala:16)
at scala.reflect.internal.MissingRequirementError$.notFound(MissingRequirementError.scala:17)
at scala.reflect.internal.Mirrors$RootsBase.getModuleOrClass(Mirrors.scala:48)
at scala.reflect.internal.Mirrors$RootsBase.getModuleOrClass(Mirrors.scala:40)
at scala.reflect.internal.Mirrors$RootsBase.getModuleOrClass(Mirrors.scala:61)
at scala.reflect.internal.Mirrors$RootsBase.getPackage(Mirrors.scala:172)
at scala.reflect.internal.Mirrors$RootsBase.getRequiredPackage(Mirrors.scala:175)
at scala.reflect.internal.Definitions$DefinitionsClass.RuntimePackage$lzycompute(Definitions.scala:181)
at scala.reflect.internal.Definitions$DefinitionsClass.RuntimePackage(Definitions.scala:181)
at scala.reflect.internal.Definitions$DefinitionsClass.RuntimePackageClass$lzycompute(Definitions.scala:182)
at scala.reflect.internal.Definitions$DefinitionsClass.RuntimePackageClass(Definitions.scala:182)
at scala.reflect.internal.Definitions$DefinitionsClass.AnnotationDefaultAttr$lzycompute(Definitions.scala:1015)
at scala.reflect.internal.Definitions$DefinitionsClass.AnnotationDefaultAttr(Definitions.scala:1014)
at scala.reflect.internal.Definitions$DefinitionsClass.syntheticCoreClasses$lzycompute(Definitions.scala:1144)
at scala.reflect.internal.Definitions$DefinitionsClass.syntheticCoreClasses(Definitions.scala:1143)
at scala.reflect.internal.Definitions$DefinitionsClass.symbolsNotPresentInBytecode$lzycompute(Definitions.scala:1187)
at scala.reflect.internal.Definitions$DefinitionsClass.symbolsNotPresentInBytecode(Definitions.scala:1187)
at scala.reflect.internal.Definitions$DefinitionsClass.init(Definitions.scala:1252)
at scala.tools.nsc.Global$Run.(Global.scala:1290)
at extract.ScalaExtractor$Compiler$2$.(ScalaExtractor.scala:24)
Working invocation:
java -Xbootclasspath/p:/path/to/home/.sbt/boot/scala-2.10.2/lib/scala-library.jar -jar /path/to/target/scala-2.10/application-assembly-1.0.jar
The strange thing about it is that the application-assembly-1.0.jar was built so that it includes all dependencies including the Scala library. When one extracts the JAR file it can be verified that the class files in the scala.runtime package have been included.
Creation of the JAR file
addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.9.1") was added to project/plugins.sbt and the assembly target was invoked. A JAR file of about 25MB results.
Building the JAR with proguard shows the same runtime behavior as seen with assembly's JAR file.
Application code that triggers the MissingRequirementError
Some application code works fine and the previously described exception is triggered as soon as the new Run from the following fragment executes.
import scala.reflect.internal.util.BatchSourceFile
import scala.reflect.io.AbstractFile
import scala.reflect.io.Path.jfile2path
import scala.tools.nsc.Global
import scala.tools.nsc.Settings
…
import scala.tools.nsc._
object Compiler extends Global(new Settings()) {
new Run // This is line 24 from the stack trace!
def parse(path: File) = {
val code = AbstractFile.getFile(path)
val bfs = new BatchSourceFile(code, code.toCharArray)
val parser = new syntaxAnalyzer.UnitParser(new CompilationUnit(bfs))
parser.smartParse()
}
}
val ast = Compiler.parse(file)
Among others, scala-library, scala-compiler and scala-reflect are defined as dependencies in build.sbt.
For the curios / background information
The aim of the application is to aid in localization of Java and Scala programs. The task of the code fragment above is to get an AST from a Scala file in order to find method calls in there.
The questions
Given the Scala library is included in the JAR file, why is necessary to call the JAR using -Xbootclasspath/p:scala-library.jar?
Why do other parts of the application run just fine even though scala.runtime is reported as missing later?
The easy way to configure the settings with familiar keystrokes:
import scala.tools.nsc.Global
import scala.tools.nsc.Settings
def main(args: Array[String]) {
val s = new Settings
s processArgumentString "-usejavacp"
val g = new Global(s)
val r = new g.Run
}
That works for your scenario.
Even easier:
java -Dscala.usejavacp=true -jar ./scall.jar
Bonus info, I happened to come across the enabling commit message:
Went ahead and implemented classpaths as described in email to
scala-internals on the theory that at this point I must know what I'm
doing.
** PUBLIC SERVICE ANNOUNCEMENT **
If your code of whatever kind stopped working with this commit (most
likely the error is something like "object scala not found") you can
get it working again with either of:
passing -usejavacp on the command line
set system property "scala.usejavacp" to "true"
Either of these will alert scala that you want the java application
classpath to be utilized by scala as well.

Scala eclipse plugin java.lang.ClassNotFoundException

I am using eclipse Version: 3.7.2 with the Scala IDE for Eclipse 2.1.0.nightly-2_09-201203121521-6e8582e. The java version is 1.6.0_31. The OS is Ubuntu 11.10.
I have looked for solutions to this problem, but I have not found one yet. I hope there is not an obvious answer that I have missed.
I have this class (note the package):
package model.x.y
import org.scalatest.FunSuite
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner
#RunWith(classOf[JUnitRunner])
class GibberishTestSuite extends FunSuite {
test("Check Gibberish") {
assert("blah" === "blah")
}
}
I am also using gradle and the source path looks like this (note that the package does not match the directory hierarchy):
.../src/test/scala/model/GibberishTest.scala
Eclipse and gradle generate the coresponding class files:
bin/model/x/y/GibberishTestSuite.class
build/classes/test/model/x/y/GibberishTestSuite.class
This runs fine through gradle, but when I try to run in eclipse, I get
Class not found model.GibberishTestSuite
java.lang.ClassNotFoundException: model.GibberishTestSuite
at java.net.URLClassLoader$1.run(URLClassLoader.java:217)
If I change the package to
package model
so that the directory hierarchy and the package name match, then I am able to run the unit test in eclipse. In scala, it is legal for the package structure and the directory structure not to match. However, the mismatch seems to be confusing eclipse or the plugin.
Am I doing something wrong? Am I missing some configuration nuance? Is this scala language feature not supported in eclipse? Will it be supported at some point?
Thank you.
This is an Eclipse (JDT) problem rather than a Scala/scala-ide problem.
There was a bug raised against Eclipse (Package Explorer tree does match declared package), but basically, Eclipse assumes that the hierarchy matches the package names. This will be fixed eventually in the Scala-ide, but the model needs to be changed, to remove the dependency on the JDT. If you want this fixed, it's a good idea to add your vote to the above issue.

Error in scala + dispatch

I am trying to GET a response from an API, using scala and dispatch. However, I get this error, after building. I googled for a solution, and tried cleaning, and resarting eclipse, but the error wont go away. What seems to be the problem? I use eclipse Helios (ie 3.6) and Scala v2.8.1, with Scala IDE v1.0.0.201104170033, installed from the Eclipse market.
dispatch{dispatch.type}.Http{object dispatch.Http} of type object dispatch.Http does not take parameters
This is my code.
class getList {
def main(args: Array[String]){
Http("http://foo.com/" >>> System.out)
}
}
What am I doing wrong?
What libraries have you downloaded? Are you sure the dependencies are set correctly? I tried with dispatch_http, version 8.0 for Scala 2.8.1, and it worked.
What imports are you using? I used these imports to make it work:
import dispatch.Http
import dispatch.HandlerVerbs._
Finally... class getList??? I assume this is a result of cut&pasting from actual code, but you should strive to produce a compilable example of your problem. Scala doesn't run programs from class, only from object, and it follows Java style of having classes start with an uppercase letter.
Here's the minimal code I used with SBT to get a working example.
Initializing:
~/test$ sbt
Project does not exist, create new project? (y/N/s) y
Name: test
Organization: test
Version [1.0]:
Scala version [2.7.7]: 2.8.1
sbt version [0.7.4]:
~/test$ cat project/build/TestProject.scala
import sbt._
class TestProject(info: ProjectInfo) extends DefaultProject(info) {
val dvers = "0.8.0"
val http = "net.databinder" %% "dispatch-http" % dvers
}
~/test$ cat src/main/scala/GetList.scala
import dispatch.Http
import dispatch.HandlerVerbs._
object GetList {
def main(args: Array[String]){
Http("http://foo.com/" >>> System.out)
}
}
~/test# sbt update run