java 调用scala 类,我可以使用scala类来实现Java的Java接口吗?

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值