Вопрос

I want to convert a mutable map into an immutable map inside of a closed scope. Here's a sample code of the situation and nonsense defensive copy:

def func(): immutable.Map[String, Int] = {
    val map = mutable.HashMap[String, Int]
    // here goes operations for the map
    return immutable.HashMap ++ map
}

As I wrote "nonsense", doing defensive copy here is totally wasting, since the mutable map is actually immutable from outside. If we can make only the getter operations seenable from outside, it should be better for the performance.

The problem is that I really don't know how to do it. I tried simply wrapping it by an anonymous immutable map instance, but the method def +[B1 >: B](kv: (A, B1)) makes it impossible.

Please help me!

EDIT: just forgot to fix the returned type [Int, Int] to [String, Int]

Это было полезно?

Решение

You can return simply collection.Map, which is a common supertype of collection.mutable.Map and collection.immutable.Map:

def func(): collection.Map[Int, Int] = {
  val map = mutable.HashMap[String, Int]
  // here goes operations for the map
  return map
}

The users could cast it to mutable.Map, but they could also get the mutable map by reflection in any solution which avoids copying, or mutate the immutable map even when you do copy.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top