Created
December 17, 2021 13:50
-
-
Save magdamiu/b3fb76a362f58fa1522617378cd41fd8 to your computer and use it in GitHub Desktop.
Disposable pattern to avoid resource leaks | High performance with idiomatic Kotlin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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