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

后端 未结 3 988
清酒与你
清酒与你 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条回答
  •  旧时难觅i
    2021-02-02 14:16

    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.

提交回复
热议问题