Can I use a scala class which implements a java interface from Java?

后端 未结 3 976
清酒与你
清酒与你 2021-02-02 13:45

I\'m learning Scala and was curious if it would be possible to:

  1. Create an object which implements a Java interface in Scala
  2. Compile the object into a clas
3条回答
  •  [愿得一人]
    2021-02-02 14:38

    I have implemented a custom org.apache.solr.handler.RequestHandlerBase and custom org.apache.solr.request.QueryResponseWriter in Scala 2.8 with Java 1.6.0 and Solr 1.4.0. I am not sure of the Lucene version Solr 1.4.0 is using but I would assume a fairly recent one. Anyway, I packaged the class files generated by Scala in a jar and Solr was able to load it just fine. So what you are trying to do is possible.

    I would say the main thing to overcome is to convert from Java collection objects like List and Vector to Scala collection objects and vice versa. scala.collection.JavaConversions in Scala 2.8.0 will probably be your friend.

    One other thing, if you need to override a method like getBooleanQuery, you may need to add [_] to make Scala compile (code not tested - but since it took me a while to figure that kind of stuff out when I started Scala, I thought I'd share):

    override def getBooleanQuery(clauses: java.util.List[_]): Query = { ... }
    

    Edit:: One more thing about the joint compilation. Daniel's information on how to joint compile is useful. You may not immediately need it though, as very likely, you just need to have scalac know the path to the Lucene jar files, then package your class in a new jar, and have your jar file used at runtime in the deployed environment.

提交回复
热议问题