I use scala.collection.immutable.HashMap<A,B> from some Java code and would like to use the Scala-native method toArray() to convert the contents (or values) of the map to an array.
I currently use JavaConversions.asMap() etc, and then use the traditional, but ugly, Java toArray(T[]) methods but I would prefer to call the Scala built in method directly instead.
This must be done from Java. Rewriting the code in Scala is not an option.
I am using Scala 2.9.1.
You need to supply a
ClassManifestfor the array type,T. This is available from the companion object (see note) forClassManifest. So:In this example,
Tis a real type (not a type parameter). So for example, ifitrwere aSeq[String], you would use this;Because scala’s
Mapis actually a bunch of tuples, you would use this:Of course, this gives you a
Tuple2[], rather than aTuple2<K,V>[]for the key and values typesKandVrespectively. As you are in Java-land, you can cast the raw typeNote: accessing the companion object from Java.
The companion object of a type
Mis available by accessing the static fieldM$.MODULE$