Creating C#'s "Using" statement in Scala
C# first introduced me to the world of functional programming, which has led me to Scala. One feature of C# that I used a lot is the using statement, which lets you write something like this:
using( var connection = new Connection(...) ) {
connection.DoStuff();
}
instead of:
Connection connection = null;
try {
connection = new Connection( ... )
connection.DoStuff();
}
finally {
connection.Dispose();
}
The first snippet of code is smaller and more concise. The using statement means you don't have to write boiler plate try-finally code to close your resources in the event of an exception.
Having just started developing in Scala, I was looking for something similar, here is an implementation of Using in Scala:
(Inspired by Beginning Scala by David Pollak creator of the Scala web framework Lift)
object Using {
/*
* Recreate C#'s Using statement
*
* Use a method called apply, which in Scala can be invoked directly off the object, e.g.
* Using(foo) instead of Using.apply(foo)
*/
def apply[A <: {def close(): Unit}, B](param: A)(f: A => B) : B =
try {
f(param)
} finally {
param.close()
}
}
Which can be used like this:
using( new Connection(...) ) { connection =>
connection.DoStuff();
}
So there are a few things going on here:
- "object Using" is the syntax for a singleton class named Using
- By naming our method "apply" we can take advantage of some Scala syntactic sugar to enable us to invoke it like "Using( ... )" instead of the traditional "Using.apply( ... )"
- The method apply takes two parameter lists, the first (param: A) has one parameter, the item to be closed, and the second (f: A => B) which takes a function which will be invoked in a try-finally clause in case it throws an exception

