Use the disposable pattern along with the try-finally construction to avoid resource leaks.
The disposable pattern is a pattern for resource management. This pattern assumes that an object represents a resource and that the resource can be released by invoking a method such as close or dispose.
The following example demonstrates how to use them:
fun readFirstLine() : String? {
......
var bufferedReader: BufferedReader? = null
return try {
......
bufferedReader = BufferedReader(inputStreamReader)
bufferedReader.readLine()
} catch (e: Exception) {
null
} finally {
......
bufferedReader?.close()
}
}
The Kotlin standard library already has extension functions that use this approach under the hood:
fun readFirstLine(): String? = File("input.txt")
.inputStream()
.bufferedReader...