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.

8 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

albina N muro said...

I miss it so in Java! However, Scala will let me make my own, complete with some nice additions. Credit Restoration

jowdjbrown said...
This comment has been removed by the author.
Elizabeth J. Neal said...

You are one step away from a Personal Loan Approval! Complete the form below to secure your loan. ... Receive funds the same day you finalize your loan. Viva Loans

jowdjbrown said...

The Institute is entirely funded by donations from its staff, friends and from proceeds from sales at our book servicesnabblån

jowdjbrown said...
This comment has been removed by the author.

Post a Comment