5

Normally, they will tell you to

import scala.io.Source
for(line <- Source.fromPath("myfile.txt").getLines())
  println(line)

which seems to leave the file open. What is a closeable counterpart?

1 Answers1

22

You can close the Source and this will close your file.

import scala.io.Source

val source = Source.fromFile("myfile.txt")
for (line <- source.getLines())
   println(line)
source.close()
Łukasz
  • 8,555
  • 2
  • 28
  • 51
  • Thanks, [this answer](http://stackoverflow.com/a/4509988/4563974) distracted me. I keep wondering, why do you all guys use fromPath instead of fromFile? My compiler says that `fromPath is not a member of Source` and I must use fromFile instead. – Valentin Tihomirov Nov 28 '15 at 14:53
  • You could also draw attention to the [using approach](http://stackoverflow.com/a/33972743/4563974) – Valentin Tihomirov Nov 28 '15 at 15:03
  • "why do you all guys use fromPath instead of fromFile?" You are one of those guys. Tbh I just copied this from your question. Actually there is no such method. I fixed my answer to use `fromFile`. – Łukasz Dec 01 '15 at 19:06