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?
A java list can be returned from a Scala program by writing a user defined method of Java in Scala. Here, we don't even need to import any Scala's JavaConversions object in order to make this conversions work. Now, lets see some examples.
Scala Seq is a trait to represent immutable sequences. This structure provides index based access and various utility methods to find elements, their occurences and subsequences. A Seq maintains the insertion order.
Scala has a rich set of collection library. Collections are containers of things. Those containers can be sequenced, linear sets of items like List, Tuple, Option, Map, etc. The collections may have an arbitrary number of elements or be bounded to zero or one element (e.g., Option).
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).
Aand I just found it:
Locale.getAvailableLocales.to[Seq]
No need for any implicit converters, or anything.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With