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 (http://msdn.microsoft.com/en-us/library/yh598w02.aspx). 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:
package com.active.scala.util

import java.io.Closeable

object Loans {
 def using[T <: Closeable, R](c: T)(action: T => R): R = {
  try {
   action(c)
  } 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.

3 comments:

lingmaaki said...

An example on ...C# using statement

Ling

albina N muro said...
This comment has been removed by the author.
albina N muro said...

Their only obligation is to keep a record of how much energy they manage to save and what they discovered in the process. www.getsomedosh.com

Post a Comment