What's the right way to use scala.io.Source?

Starting Scala 2.13, the standard library provides a dedicated resource management utility: Using.

It can be used in this case with scala.io.Source as it extends AutoCloseable in order to read from a file and, no matter what, close the file resource afterwards:

import scala.util.Using
import scala.io.Source

Using(Source.fromFile("file.txt")) { source => source.mkString }
// scala.util.Try[String] = Success("hello\nworld\n")

For the sake of completeness

val testTxtSource = scala.io.Source.fromFile("test.txt")
val str = testTxtSource.mkString()
testTxtSource.close()

Should get things done.


Scala's io library was just hack done to provide support for limited needs. There was an effort to provide a well-thought io library to Scala, which is currently hosted at assembla, with a github repository as well.

If you are going to use I/O for anything more than reading the occasional file on short-lived processes, you'd better either use Java libraries, or look at the I/O support presently available in the compiler (which will require scala-compiler.jar to be distributed with the app).

Automatic resource management is provided since Scala 2.13 in the standard library (scala.util.Using). For older Scala versions look at this question, or at this library (which is featured in the accepted answer at that question).

So, on Scala 2.13 or newer, this works correctly:

import scala.util.Using
import scala.io.Source

val tryStr: Try[String] = Using(Source.fromFile("test.txt"))(_.mkString())