简体   繁体   中英

java scala interoperability

Let say you have a scala lib that needs to be used by your java programs but not only in the future.

When it comes to collection and every goodies that you may have in scala. Would you rather create some methods specific for java in your class, or somewhat in line with the single responsibility principle, you would create a bunch of static object that provide for the method that convert your object in there scala version using explicit conversion, asjava.

If there was a way to convert asJava from within java that would be way easier, but i don't know if that package of explicit conversion can be used from within java. I doubt as i feel that it use type class to augment the functionality.

Is there anything from java that could help.

What is the best practice here.

Many thanks in advance.

Calling Scala code from Java is usually much trickier than the other way around. You can actually use asJava from Java too if you to reference the Scala standard library. As for type classes, they are really just implicits that the compiler substitutes for you automatically. In Java there are no implicits, obviously, so you need to pass the right instance yourself (which is somewhat cumbersome but doable). Here's an example of that (it's converting a Java map to a Scala one but it should work similarly the other way around): Convert java.util.HashMap to scala.collection.immutable.Map in java .

Personally I would say that you should introduce thin wrappers over the bits you want to expose to Java, which don't use any fancy Scala features like implicits, function objects (you can actually substitute those with Java 8 constructs) and such.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM