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

后端 未结 3 973
清酒与你
清酒与你 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:35

    Yes it's possible. Some of the Scala features (such as singleton objects) will compile to code which is hard to use from Java, but using Scala classes through a Java interface is an easy way to write compatible code.

    Some questions about Java interoperability are answered at http://www.scala-lang.org/faq/4 and in the book Programming in Scala. Quoted from that FAQ:

    Can I use existing Java code from Scala?

    Accessing Java classes from Scala code is no problem at all. Using a Scala class from Java can get tricky, in particular if your Scala class uses advanced features like generics, polymorphic methods, or abstract types. Since Java doesn't have such language features, you have to know something about the encoding scheme of Scala classes. Otherwise, there should be no problems.

    Do I need to convert Java data structures to Scala, and vice versa?

    You do not have to convert Java data structures at all for using them in Scala. You can use them "as is". For instance, Scala classes can subclass Java classes, you can instantiate Java classes in Scala, you can access methods, fields (even if they are static), etc.

提交回复
热议问题