What is the preferred way to return an immutable map from a locally constructed mutable?

Often I find that I implement methods that create a map from an input source. In this case, I use scala.collection.mutable.Map, assuming greater speed and efficiency; however, once this collection is built, I no longer want it to be volatile.

What is the preferred way for Scala to return an immutable card from a mutable one? Usually I do myMap.toMap, which obviously works, but it smells. Alternatively, you can set the return type to scala.collection.Map, which does not require the creation of a new collection, but it seems like this can confuse readers.

Thanks for any answers.

+3
source share
3

- .toMap. , , immutable.Map.

, scala.collection.Map . -, . immutable.Map .

+7

, , .toMap , collection.immutable.Map() ++ myMap, , . ( (), .)

; , . , , .

+5
import scala.collection._
import scala.collection.JavaConversions._

val myMap: mutable.Map[K,V] = ???
val unmodifiable: mutable.Map[K,V] =
  java.util.Collections.unmodifiableMap[K,V](myMap)
val newMap = unmodifiable.asInstanceOf[scala.collection.Map[K,V]]

You can apply newMapto mutable.Map, but changes will throw UnsupportedOperationException.

In my case, the cards can be small enough to toMapbe faster and use less memory.

0
source

All Articles