Reputation: 9771
Let's 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 the 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?
Upvotes: 1
Views: 1705
Reputation: 505
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.
Upvotes: 1