5

I am working in Java. I am calling a scala function which returns a Seq[String]. To convert it to java's List, I tried using scala.collection.JavaConverters's asJava. But this does not seem to work.

Answers on similar questions have suggested either using JavaConversions or WrapAsJava, both of which are deprecated.

Similar Question - Converting Scala seq<string> to Java List<string>

//someScalaFunc returns a Seq[String]
List<String> listA = someScalaFunc(); 

3 Answers 3

12

Since JavaConversions is deprecated, You can use JavaConverters for this:

List<String> listA = scala.collection.JavaConverters.seqAsJavaList(someScalaFunc())
Sign up to request clarification or add additional context in comments.

4 Comments

This worked fine, but I tried to import it statically, but someScalaFunc() is a generic function. Is there a way to import it in a static fashion, and avoid using class name with the function call?
import import static scala.collection.JavaConverters.seqAsJavaList and use seqAsJavaList(someScalaFunc()), Isn't it enough?
No, it gives this error - seqAsJavaList (Seq<A>) in javaconverters cannot be applied to Seq<java.lang.String> And I checked that generic functions cannot be imported in a static way, either full class name has to be used or their return value should be stored in an intermediate variable. In this case intermediate variable cannot be used to store the scala Seq.
@piyushaggarwal try JavaConverters.<String>seqAsJavaList(someScalaFunc())
2

You can use a Java to Scala implicit converter by importing the following:

import scala.collection.JavaConversions._

Comments

0
import scala.collection.JavaConverters._

val scalaList = List("A", "B", "c")

scalaList.asJava

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.