Convert from scala.collection.Seq to java.

2019-01-18 09:22发布

I'm calling a Scala method, from Java. And I need to make the conversion from Seq to List.

I can't modified the signature of the Scala method, so I can't used the asJavaCollection method from scala.collection.JavaConversions._

Any ideas of how can I achieve this?

Using Scala 2.9.3

4条回答
贪生不怕死
2楼-- · 2019-01-18 09:45

Since Scala 2.9, you shouldn't use implicits from JavaConversions since they are deprecated and will soon be removed. Instead, to convert Seq into java List use convert package like this (although it doesn't look very nice):

import scala.collection.convert.WrapAsJava$;

public class Test {
    java.util.List<String> convert(scala.collection.Seq<String> seq) {
        return WrapAsJava$.MODULE$.seqAsJavaList(seq);
    }
}
查看更多
淡お忘
3楼-- · 2019-01-18 09:46

You're on the right track using JavaConversions, but the method you need for this particular conversion is seqAsJavaList:

java.util.List<String> convert(scala.collection.Seq<String> seq) {
    return scala.collection.JavaConversions.seqAsJavaList(seq);
}
查看更多
甜甜的少女心
4楼-- · 2019-01-18 09:46

(In case you want to do this conversion in Scala code)

You can use JavaConverters to make this really easy.

import collection.JavaConverters._
val s: Seq[String] = ...
val list: java.util.List<String> = s.asJava
查看更多
成全新的幸福
5楼-- · 2019-01-18 09:51

Since 2.12 this is the recommended way:

public static <T> java.util.List<T> convert(scala.collection.Seq<T> seq) {
    return scala.collection.JavaConverters.seqAsJavaList(seq);
}

All other methods a @deprecated("use JavaConverters or consider ToJavaImplicits", since="2.12.0")

查看更多
登录 后发表回答