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

woods picture woods · Dec 16, 2010 · Viewed 32.5k times · Source

In many examples, it is described that you can use scala.io.Source to read a whole file like this:

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

But closing the underlying stream is not mentioned.

Why does Scala not provide a convenient way to do that such as with clause in Python? It looks useful but not difficult.

Is there any other better way to do that safely in Scala, I means to read a whole file?

Answer

matyjas picture matyjas · Aug 24, 2011

For the sake of completeness

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

Should get things done.