Please note that the Scala wikis are in a state of flux. We strongly encourage you to add content but avoid creating permanent links. URLs will frequently change. For our long-term plans see this post by the doc czar.
Skip to end of metadata
Go to start of metadata

'Loan' pattern

Ensures that a resource is deterministically disposed of once it goes out of scope.

The normal way to do this in Java is with a try ... finally block, which leads to ugly and fragile code, especially when there are multiple resources:

This can be improved in Scala by encapsulating the disposal code in a function which takes a closure:

The client code now looks like this:

The using function above can be generalized to arbitrary resources by letting the resource type be a type parameter. Assuming that Resource is a mixin class requiring the definition of a dispose method, one can write:

Probably best of all, though, is to provide library functions that call getResource() internally. Then we would have, for each resource, a function that looks like this:

Client code becomes very simple:

Client code now obtains the resource 'on loan', and the compiler will guarantee that it is always returned. Care must still be taken to ensure that side-effects of f do not retain references to disposed resources.

  • No labels