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
