Loan Shark - Using the Loan Pattern in Scala

Today we're going to look at elegantly using the Loan Pattern in Scala. One of my big pet peeves on Java is how convoluted it is to read lines from a simple file. You're looking at 10-15 lines of code with opening/closing resources, try catches, etc… (see here). This can be solved in Scala by making use of what's called the "Loan Pattern" (thanks to Chris Bissel for turning me on to this one). The loan pattern does exactly what it says it does, it loans a resource to a function of code. This let's you abstract away all the setup, managing, and closing of resources. Not only does this save a ton of time but it also has the side effect of reducing memory/resource leaks since the closing of those resources is abstracted away from the client code.



Here is an example of using the Loan Pattern to read lines of files in my /var/log/secure.log file and print them out to the console







As you can see the line parameter is a string that we're actually injecting into the function we created. This makes use of currying in scala by allowing you to actually define a separate curried parameter.

def withFileIterator(filename: String, encoding: String = "UTF8")(work: String => Unit) {



the "work" function we define accepts a String as the parameter which will be the line that we inject in our iterator loop. You can see the full unit test for this pattern here: LoanPatternTest.scala



Now we can look at another example of painful cruft coding, writing to a file. In this code we're going to inject an output buffer to our function so we don't have to worry about managing and closing that resource as well.







You can see here we're actually passing in our output buffer as the "ob" variable and then we can work with that object just as if we created it ourselves. It will be flushed and closed at the end of it's use



Hopefully you can start to see the value of the Loan Pattern which really simplifies working with resources. We use this also for our Redis, Database and other resources. The added bonus is that as you test and refactor you may come up with a faster, better way to read and write to your resources which gives you just one place to make those improvements, keeping the client code nicely abstracted away.



The full project is hosted at: ScalaTown - github

Ready for More?

Follow Me @jimplush