liveBook · Manning

Resource finalization

As explained in Functional Programming in Scala, Second Edition

Resource finalization is the execution of cleanup actions that release an acquired resource after computation completes or fails.

Resource finalization releases an acquired resource after its computation completes or fails. Separate acquisition, use, and release, then attach release with Stream.onComplete so cleanup belongs to the computation rather than an ad hoc success path. section 15.3.2

Reading and closing a file

Define acquire(path) as Task(Source.fromFile(path)), use(source) as a stream over source.getLines, and release(source) as Task(source.close()). Compose them with use(resource).onComplete(Stream.eval(release(resource))). The cleanup stream is attached to the use stream, including when stream evaluation reports an error. section 15.3.2

The pattern makes the lifecycle explicit:

  • Acquire the resource inside Task. section 15.3.2
  • Represent consumption as a Stream[Task, A]. section 15.3.2
  • Attach release with onComplete rather than scattering close calls through processing code. section 15.3.2

How Functional Programming in Scala, Second Edition covers it

How deep it goes
Walks through acquire, use, release, and onComplete, but stops short of a generalized bracket abstraction.
Examples
Uses a file Source, getLines, Stream.fromIterator, println, close, and Stream.onComplete.
What it assumes
Assumes familiarity with Task, Stream, flatMap, and effectful evaluation; teaches the acquire-use-release arrangement concretely.
What you can do after
Apply it via Stream.onComplete to attach cleanup to a resource-using computation.
How it connects
Connects resource finalization to Task, Stream, error handling, and effectful resource acquisition.

This explainer was generated by Manning's knowledge graph from the text of Functional Programming in Scala, Second Edition. The section links point to the parts of the book it draws on.