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?

4

2 回答 2

3

简而言之 - 不。 用给定的函数createBufferedSource创建,但从不要求不为不为BufferedSourcecloseresetclose

于 2013-08-28T03:48:50.207 回答
0

这篇文章可能会有所帮助: Scala:“使用”函数

它看起来类似于 C# using 语句,我觉得非常方便。

于 2013-08-28T08:33:12.023 回答