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
- Start with Two lines, A then B
- Do this Read one line at a time
- Result Two records
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.
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 + "]"))
}
}
[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
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.
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.