...
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.


No comments:
Post a Comment