Try-with-resources in Kotlin

Kotlin Mobile DevelopmentApps/Applications

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".

import java.io.File

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

Output

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 (https://play.kotlinlang.org/), it will throw a security exception, as you don't have permission to read from the playground server.

Exception in thread "main" java.io.FileNotFoundException: myFile.txt (No such file or directory)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at MainKt.main(main.kt:4)
raja
Updated on 23-Nov-2021 06:51:34

Advertisements