Skip to content

Instantly share code, notes, and snippets.

@magdamiu
Created December 17, 2021 13:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save magdamiu/b3fb76a362f58fa1522617378cd41fd8 to your computer and use it in GitHub Desktop.
Save magdamiu/b3fb76a362f58fa1522617378cd41fd8 to your computer and use it in GitHub Desktop.
Disposable pattern to avoid resource leaks | High performance with idiomatic Kotlin
inputStream.use {
outputStream.use {
// do something with the streams
outputStream.write(inputStream.read())
}
}
// improved option
arrayOf(inputStream, outputStream).use {
// do something with the streams
outputStream.write(inputStream.read())
}
// use implementation
private inline fun <T : Closeable?> Array<T>.use(block: ()->Unit) {
// implementation
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment