August 2018
Beginner
178 pages
4h 56m
English
The Use function extends the Closable interface and is similar to Java’s try with resources. It takes a lambda function, executes it and then closes the resource. The resource will be closed even if your lambda throws an exception:
val inputStream = "Kotlin".byteInputStream()inputStream.use { stream -> val scanner = Scanner(stream) if (scanner.hasNext()) scanner.next() else ""}
In this example, we used the lambda to read the stream. After the lambda gets executed, the use function calls close on the stream resource. Even if your lambda fails, like the next example shows, the use function will catch the exception, close the resource and then re-throw the exception:
val inputStream = "Kotlin".byteInputStream()inputStream.use { stream
Read now
Unlock full access