I have no experience with Scala, so this question may be elementary. I am trying to use Scala class from within Java, based on the "Person" example in this tutorial: http://www.codecommit.com/blog/java/interop-between-java-and-scala
I create two source files, one Scala and one Java, as follows.
Person.scala:
class Person {
def getName() = "Daniel Spiewak"
}
Test.java:
public class Test {
public static void main(String[] args) {
Person p = new Person();
p.getName();
}
}
I can compile (with a warning I don't understand), but I get a ClassNotFoundException when I try to run the program.
$ scalac Person.scala $ javac Test.java ./Person.class: warning: Cannot find annotation method 'bytes()' in type 'ScalaSignature': class file for scala.reflect.ScalaSignature not found 1 warning $ java Test Exception in thread "main" java.lang.NoClassDefFoundError: scala/ScalaObject at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:787) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142) at java.net.URLClassLoader.defineClass(URLClassLoader.java:447) at java.net.URLClassLoader.access$100(URLClassLoader.java:71) at java.net.URLClassLoader$1.run(URLClassLoader.java:361) at java.net.URLClassLoader$1.run(URLClassLoader.java:355) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:354) at java.lang.ClassLoader.loadClass(ClassLoader.java:423) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308) at java.lang.ClassLoader.loadClass(ClassLoader.java:356) at Test.main(Test.java:3) Caused by: java.lang.ClassNotFoundException: scala.ScalaObject at java.net.URLClassLoader$1.run(URLClassLoader.java:366) at java.net.URLClassLoader$1.run(URLClassLoader.java:355) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:354) at java.lang.ClassLoader.loadClass(ClassLoader.java:423) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308) at java.lang.ClassLoader.loadClass(ClassLoader.java:356) ... 13 more
Any idea what I'm doing wrong?
You need to include the Scala runtime library to be able to use Scala classes. This is the cause of both the compiler warning and the error at runtime.
Try this
java -cp .:scala-library.jar Test
(the name of the jar file might be different, but the point is to add it to your classpath).