3

In my java code, I am calling a method, from a class which is defined in Scala, and I want to use one of its methods in java. Here is how I call it and it works fine.

Seq<SomeObjectType> variableName = ScalaClass.MethodInTheScalaClass(); 

I can call this function in java in this form, but since I am calling this method from a compiled package, I can't see what it going on (and therefore I can't change it).

The problem now is that, I don't know how to iterate over the "variableName" in java (since Seq is a scala type).

How can I iterate over variableName or convert it to a Java object (e.g. List)?

1 Answer 1

3

Try this:

java.util.List<SomeObjectType> res = 
  scala.collection.JavaConverters$.MODULE$.seqAsJavaListConverter(variableName).asJava();

You could get converters list in JavaConverters documentation.

You should use JavaConverters$.MODULE$ to get JavaConverters object from Java.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! So, if I have only java (no scala) everything should work perfectly fine; right?
@Daniel: you'll need scala lib, but you'll need it anyway to use ScalaClass. In case you have plenty of such scala methods to use in java code I'd recommend you to create java-friendly ScalaClassJavaApi wrapper using scala - you could use scala in any maven java project using scala-maven-plugin.

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.