Can I use scala List directly in Java?

无人久伴 提交于 2019-11-27 20:41:59

A little java-side helper method does the trick:

import scala.collection.immutable.List;
import scala.collection.immutable.List$;
import scala.collection.immutable.$colon$colon;

public class HelloScalaList {

    public static void main (String[] args) {
        List xs = list(1,2,3);
        System.out.println(xs);
    }

    public static <T> List<T> list(T ... ts) {
        List<T> result = List$.MODULE$.empty();
        for(int i = ts.length; i > 0; i--) {
            result = new $colon$colon(ts[i - 1], result);
        }
        return result;
    }
}

[Update]

As a result of this question, I started a little project called "Scava" in order to support calls from Java to Scala: http://code.google.com/p/scava-org/

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();
  }

The problem with this syntax:

List xs = List(1, 2, 3);

is that it's Scala, not Java. When you instantiate an object like that in Scala, syntactic sugar calls the apply() method of the class' companion object. You would have to do that manually in Java.

And you aren't actually creating a scala.collection.immutable.List (which is abstract):

scala> val list = List(1,2,3)                      
list: List[Int] = List(1, 2, 3)
scala> list.getClass                               
res12: java.lang.Class[_] = class scala.collection.immutable.$colon$colon

Calling Scala from Java isn't nearly as fun as calling Java from Scala. I think you'll have an easier time converting the Scala List to a Java Collection. Using any of the Scala List higher order functions would be difficult in Java and without those, you pretty much have a Java Collection anyway.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!