FF75
FF75

Reputation: 31

What's the point of the use function in Kotlin

I'm trying to use the inline function use with a FileInputStream instead of the classic try/catch IOException so that

try {
    val is = FileInputStream(file) 
    // file handling...
}
catch (e: IOException) {
    e.printStackTrace()
}

becomes

FileInputStream(file).use { fis ->
    // do stuff with file
}

My question is, why use the function use if it stills throws exception? Do I have to wrap use in a try/catch? This seems ridiculous.

Upvotes: 1

Views: 461

Answers (2)

goedi
goedi

Reputation: 2083

From Kotlin documentation:

Executes the given block function on this resource and then closes it down correctly whether an exception is thrown or not.

When you use an object that implements the Closeable interface, you need to call the close() method when you are done with it, so it releases any system resources associated with the object.

You need to be careful and close it even when an exception is thrown. In this kind of situation that is error prone, cause you might not know or forget to handle it properly, it is better to automate this pattern. That's exactly what the use function does.

Upvotes: 3

Karol Dowbecki
Karol Dowbecki

Reputation: 44942

Your try-catch does not close the resource so you are comparing apples to oranges. If you close the resource in finally block:

val is = FileInputStream(file)
try {
    ...
} 
catch (e: IOException) {
    ...
}
finally {
    is.close()
}

is definitely more verbose than use which handles closing the resource.

Upvotes: 0

Related Questions