문제

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?)

도움이 되었습니까?

해결책

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)
  })
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top