Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling Scala code from Java with java.util.List when Scala's List is expected

I have written an API in Scala. There are a couple of entry points where I am expecting a List[SomeTrait] as input and returning a List[OtherTrait].

I am including that Jar in a Java project for use and ran into a problem trying to pass a java.util.List to a method expecting Scala's List object. I realize they are not the same and that Java doesn't know how to do the conversion. So, how do you make this work without expecting the Java caller to pass in a Scala List?

like image 297
ShatyUT Avatar asked Sep 10 '12 22:09

ShatyUT


Video Answer


1 Answers

I would love to hear other suggestions but this is the solution I have found and I couldn't find it anywhere on the Google.

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

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

I add another method like this:

//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 conversion in the call to the original method is because it will end up in an infinite loop calling itself.

This is my first attempt at posting and answering my own question...apologies if I missed some standard way to doing this. It seemed like it was worth sharing and also worth opening up for discussion on better methods as I am VERY new to Scala.

EDIT Updated code to reflect suggestion from @Luigi Plinge

like image 99
ShatyUT Avatar answered Sep 21 '22 15:09

ShatyUT