Skip to content

Instantly share code, notes, and snippets.

@manjuraj
Last active February 19, 2019 03:49
Loan pattern
// Purpose:
// - Ensures that a resource is deterministically disposed of once it goes out of scope
// - Use this pattern when working with resources that should be closed or managed after use
//
// The benefit of this pattern is that it frees the developer from the responsibility of
// explicitly managing resources
import scala.io.Source
import java.io._
def withFileIterator[A](name: String, encoding: String = "UTF-8")(func: Iterator[String] => A): A = {
val source = Source.fromFile(name, "UTF-8")
val lines = source.getLines()
try {
func(lines)
} finally {
source.close()
}
}
withFileIterator("greetings.txt") { lines =>
lines.length
}
def withFileLine[A](name: String, encoding: String = "UTF-8")(func: String => A): Unit = {
val in = new BufferedReader(new InputStreamReader(new FileInputStream(name), encoding))
try {
var line = in.readLine
while (line != null) {
func(line)
line = in.readLine
}
} finally {
in.close
}
}
withFileLine("greetings.txt")(println)
def withPrintWriter[A](name: String, append: Boolean = true)(func: PrintWriter => A): A = {
val writer = new PrintWriter(new BufferedWriter(new FileWriter(name, append)))
try {
func(writer)
} finally {
writer.close()
}
}
withPrintWriter("greetings.txt") { writer =>
writer.println("hello world!")
}
// Flattening a Loan Pattern
//
// When loaning several objects, one often ends up with nested functions which can
// be flattened using the pattern here:
// http://www.casualmiracles.com/2012/04/18/flattening-the-loan-pattern/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment