liveBook · Manning

Resource safety

As explained in Functional Programming in Scala, Second Edition

Resource safety is the property that acquired resources are released appropriately and are not accessed after release, including when errors occur.

Resource safety ensures that acquired resources are closed when no longer needed, including after exceptions, and are never accessed after release. It applies to files, network sockets, database connections, and other effectful resources. section 15.1

Listing 15.1 Counting line numbers in imperative style
def linesGt40k(filename: String): IO[Boolean] = IO:
  val src = io.Source.fromFile(filename)             #1
  try
    var count = 0
    val lines: Iterator[String] = src.getLines()     #2
    while count <= 40000 && lines.hasNext do
      lines.next                                     #3
      count += 1
    count > 40000
  finally src.close

Contrast the explicit try/finally file loop with a compositional design: imperative I/O makes the program responsible for closing the handle and intertwines counting with iteration and failure handling. section 15.1

Resource-safe streaming separates algorithmic intent from low-level resource management while supporting:

  • Automatic finalization when the producer is exhausted, evaluation terminates early, or an unhandled error occurs. section 15.6
  • Incremental, compositional transformations rather than monolithic loops that are difficult to extend. section 15.1 section 15.6
  • Dynamic allocation through flatMap, allowing nested input and output files to remain safely managed. section 15.3.4

Converting dynamically selected files

Read filenames from fahrenheits.txt, open each named file, convert its stream to Celsius, and write the joined result to celsius.txt. A stream built with flatMap lets the runner close every file handle automatically, even when exceptions occur. Reordering flatMap supports one output file per input file. section 15.3.4

How Functional Programming in Scala, Second Edition covers it

How deep it goes
Explains automatic finalization across exhaustion, early termination, and errors, then identifies acquisition and finalizer operations.
Examples
Demonstrates imperative file counting, lazy line streams, dynamic Fahrenheit-to-Celsius conversion, and multi-sink file output.
What it assumes
Assumes familiarity with effectful I/O and develops safer alternatives through Stream, Pull, Pipe, and resource operations.
What you can do after
Build resource-safe streaming programs that transform, terminate, and allocate files compositionally through Stream operations.
How it connects
Connects resource safety with stream processing, incremental I/O, effect types, Stream, Pull, Pipe, flatMap, and error handling.

Related concepts

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.