5

I'm a newbie of scala and not familiar to the stream close mechanism. I wrote some code like this.

def loadResourceAsString(path: String) = {

  val is = this.getClass().getResourceAsStream(path)

  Source.fromInputStream(is).getLines().mkString("\n")

}

I found this in scala source code. The Source would return a BufferedSource which override close method to close the input stream.

def fromInputStream(is: InputStream)(implicit codec: Codec): BufferedSource =
  createBufferedSource(is, reset = () => fromInputStream(is)(codec), close = () => is.close())(codec)

If there was exception, would scala execute the close method by its own mechanism?

Or, should I close input stream in finally block explicitly just like java?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Joe Wu
  • 727
  • 1
  • 8
  • 14

2 Answers2

3

In short - no. createBufferedSource creates BufferedSource with given close function, but never calls neither for reset not for close

1esha
  • 1,722
  • 11
  • 17
0

May be this post will be helpful: Scala: “using” function.

It looks similar to C# using statement which I find very convenient.

Community
  • 1
  • 1
user4298319
  • 432
  • 3
  • 10
  • Also look at [scala-arm](http://jsuereth.com/scala-arm/) if you need a consistent solution to resource management – pagoda_5b Aug 28 '13 at 10:41