Library contents

Scala Source.getLines and Using.resource

Source.getLines yields an iterator of lines. Using.resource closes the source after the supplied function finishes.

A simple example

Source.getLines and Using.resource

  1. Start with Two lines, A then B
  2. Do this Read one line at a time
  3. Result Two records
The line reader allows the first line to be processed before the second.

Syntax

Scala syntax
Using.resource(source)(s => s.getLines().toList)
Run this example in Scala

Save the program as Lesson.scala. Use Scala 2.13.

scalac Lesson.scala
scala Lesson

Read and close a line source

A program opens a reader to process records and can finish before reaching the last one. Keep operations inside the reader's lifetime and release the open resource when the work completes.

First output line[A]
Lesson.scala
import scala.io.Source
import scala.util.Using

object Lesson {
  def main(args: Array[String]): Unit = {
    val rows = Using.resource(Source.fromString("A\n\nB")) { source =>
      source.getLines().toList
    }
    rows.foreach(line => println("[" + line + "]"))
  }
}
Output
[A]
[]
[B]

Materialize or process the iterator while the source is open. The empty interior line is part of the input and the final line can end at EOF.

Scala documentation for Source.getLines and Using.resource

Advertisements

Read a studio sign-in sheet

A rehearsal has two names with a reserved blank row between them. Count every saved line, including an empty line between two entries. The end of input adds no extra line.

GivenAda / blank / Kim
Worked result3

Read a single shift instruction

A shop closes after recording one instruction without a final newline. Count every saved line, including an empty line between two entries. The end of input adds no extra line.

GivenLock door + EOF
Worked result1