在Scala中使用Java集合比相反更容易,但是既然你问过:
import scala.collection.immutable.*;
public class foo {
public List test() {
List nil = Nil$.MODULE$; // the empty list
$colon$colon one = $colon$colon$.MODULE$.apply((Integer) 1, nil); // 1::nil
$colon$colon two = $colon$colon$.MODULE$.apply((Integer) 2, one); // 2::1::nil
System.out.println(one);
System.out.println(two);
return two;
}
}
这使用带有scala-library的javac进行编译.jar在类路径中:
javac -classpath /opt/local/share/scala-2.9/lib/scala-library.jar foo.java
您可以从 Scala REPL 调用:
scala> (new foo).test
List(1)
List(2, 1)
res0: List[Any] = List(2, 1)
要使用Scala的Java集合,您不必做任何特别的事情:
scala> new java.util.ArrayList[Int]
res1: java.util.ArrayList[Int] = []
scala> res1.add(1)
res2: Boolean = true
scala> res1
res3: java.util.ArrayList[Int] = [1]