如何在Java代码中使用scala.collection.immutable.List [英] How to use scala.collection.immutable.List in a Java code

查看:1346
本文介绍了如何在Java代码中使用scala.collection.immutable.List的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要编写一个代码来比较Java的 ArrayList 与Scala的 List 的性能。我很难在我的Java代码中使用Scala List 。有人可以发布一个真正简单的hello world示例,说明如何在java代码中创建Scala List (在 .java file)并添加说100个随机数?

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 working in my Java code. Can some one post a real simple "hello world" example of how to create a Scala List in java code (in a .java file) and add say 100 random numbers to it?

PS:我非常擅长Java,但从未使用过Scala。

PS: I am quite good at Java but have never used Scala.

推荐答案

在Scala中使用Java集合比使用其他方法更容易,但是因为你问过:

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

使用scala-library.jar编译javac类路径:

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

您可以从Scala REPL调用:

You can invoke from the Scala REPL:

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

要使用Scala的Java集合,您不必做任何特别的事情:

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]

这篇关于如何在Java代码中使用scala.collection.immutable.List的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆