Calling Scala code with Java using java.util.List when a Scala List is expected

I wrote an API in Scala. There are a couple of entry points where I expect List [SomeTrait] as input and return List [OtherTrait].

I am including a Jar in my Java project for use and have encountered a problem trying to pass java.util.List to a method waiting for a Scala List object. I understand that they are not the same and that Java does not know how to do the conversion. So how do you do this work without expecting the Java call to go on the Scala List?

+7
source share
1 answer

I would like to hear other suggestions, but this is a solution that I found, and I could not find it anywhere on Google.

If my normal Scala entry point is a method that looks something like this:

def doSomething(things: List[Thing]): List[Result] = { ... } 

I add another way:

 //import scala.collection.JavaConversions._ import scala.collection.JavaConverters._ def doSomething(things: java.util.List[Thing]): java.util.List[Result] = doSomething(things.asScala.toList).asJava 

The explicit transformation in invoking the original method is that it will be completed in an infinite loop that calls itself.

This is my first attempt to post and answer my own question ... apologize if I missed some standard way to do this. It seems to be worth sharing, and it is also worth opening a discussion about the best methods, as I am VERY new to Scala.

EDIT Updated code to reflect offer from @Luigi Plinge

+7
source

All Articles