Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There is a variant to create an empty mutable <code>Map</code> that has default values taken from the immutable <code>Map</code>. You may store a value and override the default at any time:</p> <pre><code>scala&gt; import collection.immutable.{Map =&gt; IMap} //import collection.immutable.{Map=&gt;IMap} scala&gt; import collection.mutable.HashMap //import collection.mutable.HashMap scala&gt; val iMap = IMap(1 -&gt; "one", 2 -&gt; "two") //iMap: scala.collection.immutable.Map[Int,java.lang.String] = Map((1,one), (2,two)) scala&gt; val mMap = new HashMap[Int,String] { | override def default(key: Int): String = iMap(key) | } //mMap: scala.collection.mutable.HashMap[Int,String] = Map() scala&gt; mMap(1) //res0: String = one scala&gt; mMap(2) //res1: String = two scala&gt; mMap(3) //java.util.NoSuchElementException: key not found: 3 // at scala.collection.MapLike$class.default(MapLike.scala:223) // at scala.collection.immutable.Map$Map2.default(Map.scala:110) // at scala.collection.MapLike$class.apply(MapLike.scala:134) // at scala.collection.immutable.Map$Map2.apply(Map.scala:110) // at $anon$1.default(&lt;console&gt;:9) // at $anon$1.default(&lt;console&gt;:8) // at scala.collection.MapLike$class.apply(MapLike.scala:134).... scala&gt; mMap(2) = "three" scala&gt; mMap(2) //res4: String = three </code></pre> <p><strong>Caveat</strong> (see the comment by Rex Kerr): You will not be able to remove the elements coming from the immutable map:</p> <pre><code>scala&gt; mMap.remove(1) //res5: Option[String] = None scala&gt; mMap(1) //res6: String = one </code></pre>
 

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