Question

I often find myself writing code like this:

import scala.collection.immutable._

var foos = Map.empty[Int, Foo]

def fooOf(n: Int): Foo = {
  foos.get(n) match {
    case Some(foo) => foo
    case None =>
      val foo = new Foo(n)
      foos = foos.updated(n, foo)
      foo
  }
}

With a concurrent map, the code looks much nicer:

import scala.collection.concurrent._

var foos = TrieMap.empty[Int, Foo]

def fooOf(n: Int): Foo = {
  val foo = new Foo(n)
  foos.putIfAbsent(n, foo) getOrElse foo
}

But I really want a non-concurrent, immutable map. Is there something like putIfAbsent for it?

(By the way, in the concurrent example, is it possible to create the Foo only if it is indeed absent?)

Était-ce utile?

La solution

If you're okay with a mutable variable (and seems like you are as you used var foos in both examples and only specified an immutable collection) this should match your needs:

var foos = Map.empty[Int, Foo]

def fooOf(n: Int): Foo = {
  foos.getOrElse(n, {
    foos = foos.updated(n, new Foo(n))
    foos(n)
  })
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top