Here I am going to modify the loan pattern described in this article “Scala Knol : Understanding Load Pattern” .
Let us take an example from earlier blog, we have all used connections to get to the database and then we need to destroy the connection so that there are no leaks. OK, we can use the connection factory but let us assume that we do not have that for now. The general code would look like this
Here this is a higher order function which takes a function f as an argument. function f takes connection as an argument and returns Int.
f: Connection => Int
User just need to pass the above function in doLoanSqlCall factory method. Function executeMySqlFunction do not need to worry about the creating and deleting the connection. All these stuff would be handled by the method doLoanSqlCall.
Hence the call becomes
Example given in this article is excellent if function is not expected to return any other value but Integer. It is working fine in case of most of the insert or update operation where Sql operation returns Integer values.
What is a problem is this approach ?
There is a obvious scenario where data is fetched from database then a custom object is created and returned by the function.
Suppose you have to execute following jdbc code and return an object instead of Integer then above described loan pattern will not help you.
Here mysql function is taking Connection as an argument and returning any generic type. ( In this case it is returning Optiont[List[Int]] but it can return any generic type)
So, Function defination is as follows
Connection => R
Now we need a factory method which need to accept a function f: Connection => R , instead of f: Connection => Int. The modified version of doLoanSqlCall is as follows
This version of doLoanSqlCall method will take a function which takes connection as an argument and return Option of any generic type.
Use executeMySqlFunction as closure
Following example explains the practical way of using the loan pattern with the help of closure.