Can I use scala List directly in Java?

Visus Zhao picture Visus Zhao · Dec 24, 2010 · Viewed 10.8k times · Source

Can I use scala List in Java, like :

import scala.collection.immutable.List;
class HelloScalaList {
    public static void main (String[] args) {
        List xs = List(1, 2, 3);
        System.out.println(xs);
    }
}

It does not seem to compile. can't find List$.apply method.

when I change it to

List xs = Dir.ls()

where Dir is my scala class, and ls() returns a scala List, the compiler complaints about

"Internal compiler error: java.lang.ClassCastException: org.eclipse.jdt.internal.compiler.lookup.BaseTypeBinding cannot be cast to org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding at org.eclipse.jdt.internal.compiler.lookup.BinaryTypeBinding.initializeTypeVariable(BinaryTypeBinding.java:927)"

which I have no idea what it means.


I want to write some library in scala, but would also like it to be used in Java.

In my scala class there are methods that return scala List, for java code to use them, I have two options:

  1. use scala List in java directly

  2. write a wrapper class that returns java.util.List for those methods.

I'd rather like option 1, because otherwise I'll have to write a wrapper class for nearly ALL my scala classes.

But I just can't get scala List running in Java.

Answer

Sebastien Lorber picture Sebastien Lorber · Jul 16, 2013

As of Scala 2.10, I didn't succeed with the tricks above.

But you can use the following code:

  public static <T> scala.collection.immutable.List<T> scalaList(List<T> javaList) {
    return scala.collection.JavaConversions.asScalaIterable(javaList).toList();
  }