How to use scala.collection.immutable.List in a Java code

前端 未结 4 1911
轮回少年
轮回少年 2020-12-17 15:17

I need to write a code that compares performance of Java\'s ArrayList with Scala\'s List. I am having a hard time getting the Scala List

4条回答
  •  甜味超标
    2020-12-17 15:37

    It's easier to use Java collections in Scala than the other way around, but since you asked:

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

    This compiles with javac with scala-library.jar in the classpath:

    javac -classpath /opt/local/share/scala-2.9/lib/scala-library.jar foo.java
    

    You can invoke from the Scala REPL:

    scala> (new foo).test
    List(1)
    List(2, 1)
    res0: List[Any] = List(2, 1)
    

    To use a Java collection from Scala, you don't have to do anything special:

    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]
    

提交回复
热议问题