Would scala close the InputStream automatically?

坚强是说给别人听的谎言 提交于 2020-02-03 09:10:30

问题


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?


回答1:


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




回答2:


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

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



来源:https://stackoverflow.com/questions/18478455/would-scala-close-the-inputstream-automatically

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!