5

I would like to map over a Java array in Scala. For normal Java collections, I know I could use

import scala.collection.JavaConverters._

new java.util.ArrayList[Int](1).asScala.map(_.toString)

However, for an array this conversion doesn't work:

import scala.collection.JavaConverters._

java.util.Locale.getAvailableLocales.asScala // doesn't compile

So how do I convert a Java array to a Scala collection or iterable or something I can map on?

2 Answers 2

5

You don't have to import any implicit conversion for the map to be available over Java arrays. Try running the following in Scala shell:

java.util.Locale.getAvailableLocales.map(_.toString)

The implicit conversion that allows the usage functions like map and filter over Java arrays comes with the Predef, which is imported implicitly.

As you mentioned in your own answer you can also explicitly convert an Array to another collection (which is possible thanks to the implicit conversion I mentioned previously).

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

1 Comment

Huh. I thought IntelliJ was telling me it didn't work. Oh well.
4

Aand I just found it:

Locale.getAvailableLocales.to[Seq]

No need for any implicit converters, or anything.

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.