Zoltán Zoltán - 4 months ago 20
Scala Question

Convert Java array to Scala collection

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?

Answer

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).

Comments