Function Values and the Loan Pattern

Suppose you have a Resource class:

 class​ Resource {
  println(​"Creating Resource"​)
 
 def​ someop1() { println(​"someop1"​) }
 def​ someop2() { println(​"someop2"​) }
 
 def​ close() { println(​"cleaning-up..."​) }
 }

If an instance of Resource takes up significant resources outside the JVM, like database connections, open files, handles to external systems with significant memory usage, and so on, you’d want to clean up the resource quickly after use. You can’t rely on the JVM’s garbage collector (GC), as you can’t predict when it would run, and your memory usage within the JVM may be too low to trigger the GC reasonably soon to clean up the external resources. Users of your class may be tempted ...

Get Functional Programming: A PragPub Anthology now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.