Version 2, last updated by Chris Hagan at 19 Jan 19:18 UTC
SessionMemoize
SessionVar and RequestVar are well documented in Chapter 3 of Exploring Lift so I thought I would go into SessionMemoize a little bit.
Basically it's like a Map, tied to your session. You should generally use it for values you only want to calculate once, because they're expensive to calculate and don't change often. Conveniently, it offers a way to encapsulate the following sequence of operations:
- Check whether the value is available in the map (containsKey)
- Use the value if available
- Calculate the value if not available
- Store the value for next time
- Return the calculated value
mySessionMemoObject.get(key,valueToInsertIfNotFound)The value will not be evaluated if the key is present. One thing that you should be careful of is that, unlike SessionVars, all SessionMemoize instances belonging to a session share underlying state. So these will not conflict:
object myMemo extends SessionVar[Int](1) object myOtherMemo extends SessionVar[Int](2) myMemo.is -> 1 myMemo.is -> 2But these might surprise you, because the parameter of the second call will not be evaluated - the map already contains the key.
object myMemo extends SessionMemoize[Int,String] object myOtherMemo extends SessionMemoize[Int,String] myMemo(1,"Belongs to the first memo") myOtherMemo(1,"Belongs to the second memo")
myOtherMemo(1) -> "Belongs to the first memo")If the two SessionMemoize objects are differently parametrically typed, you will get a very confusing runtime exception.