Accessing request parameters from inside a Future in Scalatra

Scalatra is an awesome, lightweight web framework for Scala. It’s perfect for building REST APIs. One of its less known features is support for asynchronous programming using Scala’s Futures.

By mixing in the FutureSupport trait one can easily make their servlet asynchronous. Once this trait is mixed-in into your servlet class, you can return Futures in your post and get handlers and Scalatra will automagically take care of them.

Recently I encountered a minor issue with Scalatra’s support for Futures – it is not possible to access params or request values from code inside a Future. The below code throws a NullPointerException.

Scalatra exposes access to contextual data such as the current user or request parameters via members such as params or request. These values are implemeted as DynamicVariables. Dynamic variables is Scala’s feature which allows a val to have different values in different scopes. The point is that DynamicVariable implementation is based on Java’s ThreadLocal. Therefore, when executing code in a Future you may not rely on these values since you might be on another thread!

read more

Combining two objects in lodash

I’m a huge fan of the lodash library. It encourages functional programming style in JavaScript and as a result lets you write less error-prone and more readable code.

Some time ago I discovered the assign (extend) function which copies properties from target object(s) and assigns them to the target object. It also returns the target object. This is very handy whenever you want to combine properties from two objects into one object.

For example, given these two objects:

…instead of copying properties manually:

…one could write:

The result in c would be the same. However, with assign, object a will be modified. What I often wanted to do is to “merge” a and into c but not modify neither a nor .

read more

Scala for C# developers – part III

I’m back from a rather lenghty break and would like to continue the Scala for C# developers series. So far I have covered the syntax, the basics of OO in Scala and functions. In this post I will look at the Option type and pattern matching.

Issues with null references

If you have programmed in C# (or Java, or any other language that supports null references) you must already know the pain of NullReferenceException. This exception is thrown whenever you are expecting that a variable points to an actual object but in reality it does not point to anything. Therefore, calling a method on such reference would result in the exception.

read more