Zoltán Zoltán - 2 months ago 13
Scala Question

Convert Java array to Scala collection

I would like to

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?


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:


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