Monday, March 7, 2011

C# using is the loan pattern in Scala

One of the remarkably handy little features of C# is the using statement ( I miss it so in Java! However, Scala will let me make my own, complete with some nice additions. Using relies on IDisposeable for cleanup; for example purposes we'll use Java's Closeable. Our goal is to be able to write code similar to:
using(new FileWriter(file)) { fw => fw append code }
Simple but pretty cool. Our FileWriter could be any Closeable. This code breaks down like this:
using is just a Scala function:


object Loans {
 def using[T <: Closeable, R](c: T)(action: T => R): R = {
  try {
  } finally {
   if (null != c) c.close
And again with some notes:
Note that we can return a value from the Scala using if we wish. This is a simple example of the loan pattern in Scala. We can apply this to any resource we would typically have to use in a try { ... } finally { cleanup my resource } structure in Java.

1 comment:

Post a Comment