Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call Scala code from Java?

I'm using Netbeans to write Scala and Java.

Netbeans generated a .jar file for the Scala project. I tried importing that file in the Java project. But I couldn't import any class from that .jar file into my Java project.

I also tried importing scala-library.jar to the java project, and could import classes from that jar.

I want to write my library in Scala, then expose a small interface that only involves Java stuff, then write a Java wrapper so that people can use it as a Java package. Is that possible? How do I do it?

Thank you very much.

like image 281
Phil Avatar asked Sep 03 '09 06:09

Phil


People also ask

Can I call Scala code from Java?

Yes, Scala classes can be called from Java and vice versa.

Can we call Scala by Java and Java by Scala?

Yes, there is the ability to mix both types of code. It is possible to create an SBT project, put Scala code in src/main/scala and java code in src/main/java in the same project and make it work.

How do you call a class from a Scala class in Java?

Calling methods on Scala instances work exactly as in Java.ScalaClass scalaClass = new ScalaClass(true); assertEquals(2, scalaClass. plus(1, 1)); Note that Scala classes cannot have static methods. The convention is to put methods of static nature on companion objects.

Can you import Scala into Java?

A Scala trait with no method implementation is just an interface at the bytecode level and can thus be used in Java code like any other interface.


1 Answers

There should be no problem in doing this.

  1. Have you verified (e.g. using WinZip or the jar utility) that your .jar file actually contains the relevant .class files? (use jar tvf mylib.jar to check)
  2. If you have verified that the correct .class files exist in your jar file, what is the runtime error you are seeing? Is it a NoClassDefFoundError? If so, which class cannot be found? How are you referring to the (Scala) class in your (Java) code?
like image 175
oxbow_lakes Avatar answered Oct 10 '22 13:10

oxbow_lakes