The disposable pattern
Use the disposable pattern along with the try-finally
construction to avoid resource leaks.
Note
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() .use { it.readLine() }
You should also remember the dispose
method when you work with the RxJava
library:
fun main(vars:...