I'm learning Scala and was curious if it would be possible to:
Create an object which implements a Java interface in Scala
Compile the object into a class file and jar it
Use the object from Java
I want to implement a custom lucene query parser in scala and be able to let others access it from a java application.
解决方案
I'm assuming that by "object" you actually mean "class". In any case, the answer is yes, you can do this. You will need to take advantage of the Scala/Java joint compiler if you want this all in the same project. For example:
public interface Parser {
public TokenIterator parse(InputStream is);
}
Then in Scala:
class ParserImpl extends Parser {
def parse(is: InputStream) = ...
}
Finally, in Java again:
public class Consumer {
public static void main(String[] args) {
Parser p = new ParserImpl(); // just like a Java class!
...
}
}
If all of these source files are in the same project, then you will want to compile them using the following invocation of commands:
$ scalac *.scala *.java
$ javac -classpath . *.java
The first command invokes the Scala/Java joint compiler, which will compile the Scala sources and just enough of the Java sources to satisfy any dependencies. The second command invokes the Java compiler with the recently-compiled Scala classes on the classpath.