As the documentation that you pointed to explains, immutable maps already are implemented under the hood as HashTrieMap
s. You can easily verify this in the REPL:
scala> println( Map(1->"one", 2->"two", 3->"three", 4->"four", 5->"five").getClass )
class scala.collection.immutable.HashMap$HashTrieMap
So you have nothing special to do, your code already is using HashMap.HashTrieMap
without you even realizing.
More precisely, the default implementation of immutable.Map
is immutable.HashMap
, which is further refined (extended) by immutable.HashMap.HashTrieMap
.
Note though that small immutable maps are not instances of immutable.HashMap.HashTrieMap
, but are implemented as special cases (this is an optimization). There is a certain size threshold where they start being impelmented as immutable.HashMap.HashTrieMap
.
As an example, entering the following in the REPL:
val m0 = HashMap[Int,String]()
val m1 = m0 + (1 -> "one")
val m2 = m1 + (2 -> "two")
val m3 = m2 + (3 -> "three")
println(s"m0: ${m0.getClass.getSimpleName}, m1: ${m1.getClass.getSimpleName}, m2: ${m2.getClass.getSimpleName}, m3: ${m3.getClass.getSimpleName}")
will print this:
m0: EmptyHashMap$, m1: HashMap1, m2: HashTrieMap, m3: HashTrieMap
So here the empty map is an instance of EmptyHashMap$
. Adding an element to that gives a HashMap1
, and adding yet another element finally gives a HashTrieMap
.
Finally, the use of withDefaultValue
does not change anything, as withDefaultValue
will just return an instance Map.WithDefault
wich wraps the initial map (which will still be a HashMap.HashTrieMap
).