How to call Scala HashMap.toArray () from Java?

I am using scala.collection.immutable.HashMap<A,B> from some Java code and would like to use the Scala native toArray() method 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 methods toArray(T[]) , but I would prefer to call the Scala built-in method instead.

This should be done with Java. Rewriting code in Scala is not an option.

I am using Scala 2.9.1.

+4
source share
4 answers

You need to specify ClassManifest for the array type, T This is accessible by a companion object (see Note) for ClassManifest . So:

 itr.toArray(ClassManifest$.MODULE$.fromClass(T.class)); 

In this example, T is a real type (not a type parameter). For example, if itr was Seq[String] , you should use this:

 itr.toArray(ClassManifest$.MODULE$.fromClass(String.class)); 

Since scala Map is actually a collection of tuples, you should use this:

 map.toArray(ClassManifest$.MODULE$.fromClass(Tuple2.class)); 

Of course, this gives you Tuple2[] , not Tuple2<K,V>[] for the keys and value types K and V respectively. Since you are in Java-land, you can use the original type

<h / "> Note : access to a companion object from Java.

A companion object of type M is accessible by accessing the static field M$.MODULE$

+2
source

That should be enough:

 map.toArray(scala.reflect.ClassManifest$.MODULE$.Object); 
+1
source

Judging by the API docs, it seems to you that you need to specify an argument of type Manifest (or ArrayTag , depending on the version) on toArray .

0
source

calling scala specific methods from java can sometimes be very ugly, as in this case. I don't know if there is a better solution for this, but this should work:

 import scala.collection.immutable.HashMap; import scala.Tuple2; import scala.reflect.ClassManifest$; import scala.reflect.ClassManifest; public class Foo { public static void main(String[] args) { HashMap<String,String> map = new HashMap(); Object ar = map.<Tuple2<String,String>>toArray((ClassManifest<Tuple2<String,String>>)ClassManifest$.MODULE$.fromClass(new Tuple2<String,String>("","").getClass())); System.out.println(ar.toString()); } } 

I don’t know how to get Class<Tuple2<String,String>> in Java without first creating it. In scala, I would use classOf[...] , is there an equivalent in java?

0
source

Source: https://habr.com/ru/post/1412374/


All Articles