Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Would scala close the InputStream automatically?

Tags:

stream

scala

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?

like image 361
Joe Wu Avatar asked Oct 22 '22 02:10

Joe Wu


1 Answers

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

like image 176
1esha Avatar answered Nov 15 '22 06:11

1esha