Lazy vals with implicit parameters
Lazy vals were an excellent addition to Scala 2.6.0. They allow you to defer calculation of a value until it is actually needed, after which the calculated value is cached.
Unfortunately, this doesn’t play so well with another wonderful Scala feature — implicit parameters. It’s often the case that you’ll want to defer resolution of an implicit until a method call, rather than in the scope of object creation. But lazy values cannot take any parameters, implicit or otherwise — so it seems you’re stuck.
Memoized to the rescue! This is a simple helper class that takes care of the caching of a result. Where you might have had the following method with an implicit parameter:
def foo(implicit bar: Bar): ResultType = { ... }
you instead write the following:
private var _foo = Memoized[ResultType] def foo(implicit bar: Bar) = _foo or { ... }
(complete source below the fold)
That’s it; nothing fancy. This is not a true memoization solution for a function that takes a parameter — check out the memo package in Scalaz for that. But I’ve found it handy, and you might too.
class Memoized[T] { private var value: Option[T] = None def isEmpty = value.isEmpty def isDefined = ! isEmpty def get: T = value.get def set(newValue: T) { value = Some(newValue) } def getOrSet( newValue: => T): T = if (isDefined) get else { set(newValue) get } def or( newValue: => T): T = getOrSet(newValue) override def toString = value.toString } object Memoized { def apply[T] = new Memoized[T] }



