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!

An obvious solution to this problem is to retrieve request parameters before entering the Future:

However, this is not always a very convenient solution. I came up with the following workaround:

Firstly, we take a copy of the current request. Later, inside the Future we tell Scalatra to substitute the request dynamic variable’s value with our copy. Therefore, the call to params will use the correct request and there will be no error.


As I recently learned, there is a much better way to solve this issue that is actually built into Scalatra. The way to go is using the AsyncResult  class. Our example would look like this:

AsyncResult  is an abstract class. We create an instance of anonymous type that extends it and overrides is  value. AsyncResult  takes copies of current request  and response  values when created and makes them available to code inside is .

You can find more information here.


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 b into c but not modify neither a nor b.

Recently I learnt that the way to do this is the following:

With above code we copy properties of a and b into a new empty object and than return this new object. This is exactly what we wanted to achieve.

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.

There is a famous quote from Tony Hoare who introduced the concept of null references claiming that it was his billion-dollar mistake:

I call it my billion-dollar mistake. It was the invention of the null reference in 1965. At that time, I was designing the first comprehensive type system for references in an object oriented language (ALGOL W). My goal was to ensure that all use of references should be absolutely safe, with checking performed automatically by the compiler. But I couldn’t resist the temptation to put in a null reference, simply because it was so easy to implement. This has led to innumerable errors, vulnerabilities, and system crashes, which have probably caused a billion dollars of pain and damage in the last forty years.

The Option type

What does it mean when a NullReferenceException is thrown? As I said, it means that the CLR was expecting a reference to an object but found an empty refence and does not know what to do with it. In the majority of cases, it means that you as the programmer should have thought about it and check for the null reference before doing anything with it. Unfortunately, it would require some great discipline to keep track of all references that could become null and to take care of each and every one of them.

The Option type comes to rescue. The idea is to force the compiler to do the hard work for you.

Option[T] is an abstract type which has two subclasses: Some[T] and None. For example, a value of type Option[Int] represents an object that can, but does not have to hold some integer. If this Option is an instance of Some than the object has some value. If it’s None than it does not have any value.

So, None is like null except we explicitly declare that an object can be None by making it an Option. If we decide to use Option types in our project we must forget about null references completly. Therefore, whenever we expect a value of type T to be optional, we must declare it as Option[T]. Thanks to that, the compiler will forbid us from writing such code:

For this to compile, we must explicitly handle the case when the provided argument is undefined.

Such code, although lengthier, is much, much safer than traditional code which allows use of null references.

Of course, the key thing is to make sure that there is never a null inside Some value. However, this is easy to ensure as long as we decide not to use null references in the whole project.

Pattern matching

The above code snippet introduces some new syntax. The match
construct is the Scala syntax for pattern matching. It is a very powerful tool common in functional programming. You can think of it as a much more advanced switch statement which always returns a value as a whole.

In the above example, the value of textOpt is examined. It is an instance of Option type and we know that it has two subclasses. Therefore, there are two case branches. The first branch demonstrates how the value contained inside Some[T] can be extracted.

Pattern matching can be used with simple types:

Additionally, pattern matching works very well with case classes which we discussed in the previous post.