using

How to open and read text files in Scala

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 12.1, “How to open and read a text file in Scala.”

Back to top

Problem

You want to open a plain-text file in Scala and process the lines in that file.

Back to top

Solution

There are two primary ways to open and read a text file:

Table of Contents

  1. Problem
  2. Solution
Back to top

The ‘using’ control structure in Beginning Scala (by David Pollak)

In David Pollak's book, Beginning Scala, he introduces a using control structure that is helpful in several ways. First, it can be used to automatically close any resource that has a close method. Second, it's a great example of how to create a custom control structure in Scala.

Introduction

Here's the source code for the using control structure he created: