13

I have a Scala array of strings:

val names:Array[String] = something.map(...)

I need to call an Android(java) method that accepts a Collection

public void addAll (Collection<? extends T> collection)

How do I covert the Array to a Collection?

2 Answers 2

21

Java approach:

java.util.Arrays.asList(names: _*)

Scala approach:

import collection.JavaConversions._

val namesColl: java.util.Collection[String] = names.toSeq

In the latter approach names array is first converted to Seq[String] and then an implicit conversion located in JavaConversions figures out that Java collection is needed so it applies necessary transformation trasparently. Don't worry, it is constant in time.

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

7 Comments

Thanks, but what do you mean by "Java approach"?
@Steve: I added the "Scala approach" as well :-).
Perfect, thank you for the explanation. Any reason why you would choose one over the other?
@DanielC.Sobral: As far as I can tell Arrays.asList creates one wrapper while toSeq and implicit conversion - two. In both cases there is no copying of an array, hence constant time complexity. So the difference is minimal, but I agree.
Please, can you explain what is the logic behind the " _* ", it works but I don't understand. When you type "name:" I guess that you are operating over names, with a sort of dynamic collection, and then you return it, right? What is exactly "names: _*" returning? if Java Arrays are the same as Scala arrays why doen't work directly?
|
4

JavaConversions is now deprecated. You should use JavaConverters instead.

import collection.JavaConverters.asJavaCollection
val collection = asJavaCollection(Array("some value"))

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.