How did I meet with DynamicVariable?

I wanna use Scalatra

with Eclise & WTP!

I added dependency using maven plugin. And made some servlet like this.

class MyServlet extends ScalatraServlet {
  get("/") {

It didn't work.

(Should I use ScalatraFilter instead of ScalaServlet?)

I googled "ScalatraServlet.scala",

and the result is ...

Sourcecode Cross Reference(SXR)

Description of SXR

Latest Source

   * A dynamic variable containing the currently-scoped response.  Should
   * not typically be invoked directly.  Prefer `response`.
   * @see #response
  protected val _response   = new DynamicVariable[HttpServletResponse](null)

   * A dynamic variable containing the currently-scoped request.  Should
   * not typically be invoked directly.  Prefer `request`.
   * @see #request
  protected val _request    = new DynamicVariable[HttpServletRequest](null)

First contact

  protected val _req = new DynamicVariable[HttpServletRequest](null)
  protected val _res = new DynamicVariable[HttpServletResponse](null)
  implicit def req = _req value
  implicit def res = _res value

In my source

I could not understand '(=> S)'

I used 'value_' at that time.

What is the name of '(=> S)'?

Is it 'Block'?

'Call by name'

I could write this function within 3 hour and 100 lines.

Scala is so powerful!

I was thiking in bathroom.

"Servlet is single thread - multi instance model, isn't it? It might be no more support for SingleThreadModel interface."

Next day, I went to office and thought about DynamicValiable.

I had already seen '(=> S)' in Scalatra get() method.

get("/") {
protected def get(path: String)(action: => String): Unit = addRoute(GET, path, action)

'=> S' : call by name

'()=> S' : no args lambda expression

_req.withValue(req) {
  _res.withValue(res) {

I remembered Java's ThreadLocal like this.

It is extended from 'InheritableThreadLocal'

"This class extends ThreadLocal to provide inheritance of values from parent thread to child thread"

ThreadLocal has varibale value depends on caller function. It is good in Framework or common libraries.

But do not recommended for amateurs.


  • Can take various values.
  • Better than Java's TreadLocal since scope is so clearly
  • Do no use so often



By hakaicode


  • 712