Try-with-resources in Kotlin

Kotlin is very efficient in managing the memory. Unlike Java, developers in Kotlin need not have to manage the memory explicitly. We do have different kinds of memory management techniques and Try-with-resource is one of them. In Kotlin, we have a function called 'use' which takes the burden of managing the resources automatically. This is a part of std library function provided by Kotlin.

As per Kotlin documentation, use() is defined as a generic extension on all closeable types. The implementation looks like this −

public inline fun <T : Closeable?, R>T.use(block: (T) -> R): R {}
  • In the above function, the definition block is the function that processes the closeable resource.

  • fun is the function call which returns the result of the block function.

Example: use() Implementation

In this example, we will see how to use the use() function in order to implement try-with-resources. We will use the use() method on bufferedReader() to read the content of "myFile.txt".


fun main(args: Array<String>) {
   val readMyFile = File("myFile.txt")
   readMyFile .bufferedReader().use{


Once the above piece of code is executed, it should read all the content of the file provided inside the file object. If you run it in Kotlin playground (, it will throw a security exception, as you don't have permission to read from the playground server.

Exception in thread "main" myFile.txt (No such file or directory)
at Method)
at MainKt.main(main.kt:4)

Updated on: 23-Nov-2021


Kickstart Your Career

Get certified by completing the course

Get Started