Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to convert from from java.util.Map to a Scala Map
    primarykey
    data
    text
    <p>A Java API returns a <code>java.util.Map&lt;java.lang.String,java.lang.Boolean&gt;</code>;. I would like to put that into a <code>Map[String,Boolean]</code></p> <p>So imagine we have:</p> <pre><code>var scalaMap : Map[String,Boolean] = Map.empty val javaMap = new JavaClass().map() // Returns java.util.Map&lt;java.lang.String,java.lang.Boolean&gt; </code></pre> <p>You can't do <code>Map.empty ++ javaMap</code>, because the ++ method does not know about Java maps. I tried:</p> <pre><code>scalaMap = Map.empty ++ new collection.jcl.MapWrapper[String,Boolean] { override def underlying = javaMap } </code></pre> <p>and:</p> <pre><code>scalaMap = Map.empty ++ new collection.jcl.MapWrapper[java.lang.String,java.lang.Boolean] { override def underlying = javaMap } </code></pre> <p>These both fail to compile, because of the generics - <code>java.lang.String</code> is not the same as a scala String.</p> <p>Is there a good way of doing this, short of copying the map manually?</p> <p>EDIT: Thanks, all good answers, I learned a lot from all of them. However, I made a mistake by posting a simpler problem here than the one I actually have. So, if you allow me, I'll generalise the question - What the API actually returns is</p> <pre><code>java.util.Map&lt;java.lang.String, java.util.Map&lt;SomeJavaEnum,java.lang.String&gt;&gt; </code></pre> <p>And I need to move this to Map[String, Map[SomeJavaEnum,String]]</p> <p>It probably does not seem like too much of a complication, but it adds an extra level of type erasure, and the only way I found of moving this to a Scala map was deep-copying it (using some of the techniques you suggested below). Anyone any hints? I kind of solved my problem by defining an implicit conversion for my exact types, so at least the ugliness is hidden in its own trait, but still feels a bit clumsy deep copying the lot.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload