tags:

views:

97

answers:

2

This page has a description of Map's getOrElseUpdate usage method:

object WithCache{
  val cacheFun1 = collection.mutable.Map[Int, Int]()
  def fun1(i:Int) = i*i
  def catchedFun1(i:Int) = cacheFun1.getOrElseUpdate(i, fun1(i))
}

So you can use catchedFun1 which will check if cacheFun1 contains key and return value associated with it. Otherwise, it will invoke fun1->cache fun1' result in cacheFun1->return fun1's result.

I can see one potencial danger - cacheFun1 can became to large. So cacheFun1 must be cleaned somehow by garbage collector?

P.S. What about scala.collection.mutable.WeekHashMap and java.lang.ref.* ?

+1  A: 

On the scala mailing list they sometimes point to the MapMaker in the Google collections library. You might want to have a look at that.

Debilski
+5  A: 

See the Memo pattern and the Scalaz implementation of said paper.

Also check out a STM implementation such as Akkas.

Not that this is only local caching so you might want to lookinto a distributed cache or STM such as CCSTM, Terracotta

oluies
Only that the *Memo Pattern* uses `WeahHashMap` and is therefore not a very good cache.
Debilski