Lai Yu-Hsuan
Lai Yu-Hsuan

Reputation: 28071

Is there a 'lazy map'?

Just like Stream is a lazy Seq, is there a lazy version of Map?

What I want to do:

val lm = LazyMap[Int, String]((a) => {
  println("only once")
  (a * a).toString()
})
lm.get(10) // print "only once"
lm.get(10) // print nothing

Upvotes: 19

Views: 6156

Answers (2)

Régis Jean-Gilles
Régis Jean-Gilles

Reputation: 32719

You are basically asking for a cache. You might have a shot at using scalaz.Memo, which adds memoization to a given function. See http://eed3si9n.com/learning-scalaz/Memo.html

This would give something like:

val lm: Int => String = Memo.mutableHashMapMemo[Int, String] { a =>
  println("only once")
  (a * a).toString()
}

Note however that what you get is a function, not a map. This means that you cannot test for the presence or absence of a given key, you can only apply. But if I am to trust your example, in your case this is exactly what you want.

Upvotes: 13

Mark
Mark

Reputation: 1181

mutable.Map provides the method getOrElseUpdate(key: A, op: ⇒ B): B. You could use that to implement lazy semantics.

You should wrap the class in another class though, because else the value can be changed later by anyone who has the reference to that map.

Upvotes: 12

Related Questions