When I read the source of scalatra, I found there are some code like:
protected val _response = new DynamicVariable[HttpServletResponse](null)
protected val _request = new DynamicVariable[HttpServletRequest](null)
There is an interesting class named DynamicVariable. I've looked at the doc of this class, but I don't know when and why we should use it? It has a withValue() which is usually be used.
If we don't use it, then what code we should use instead, to solve the problem it solved?
(I'm new to scala, if you can provide some code, that will be great)
DynamicVariableis an implementation of the loan and dynamic scope patterns. Use-case ofDynamicVariableis pretty much similar toThreadLocalin Java (as a matter of fact,DynamicVariableusesInheritableThreadLocalbehind the scenes) - it's used, when you need to do a computation within an enclosed scope, where every thread has it's own copy of the variable's value:Given that
DynamicVariableuses an inheritableThreadLocal, value of the variable is passed to the threads spawned in the context:DynamicVariable(andThreadLocal) is used in Scalatra for the same reason it's used in many other frameworks (Lift, Spring, Struts, etc.) - it's a non-intrusive way to store and pass around context(thread)-specific information.Making
HttpServletResponseandHttpServletRequestdynamic variables (and, thus, binding to a specific thread that processes request) is just the easiest way to obtain them anywhere in the code (not passing through method arguments or anyhow else explicitly).