Kotlin Use function

Kotlin Use function is an inline function used to execute given block function on this resource. Use function closes the resource correctly once after the operation is completed. There is an added benefit that even if there is an exception while executing the given block function, it is expected that the resource is closed down correctly.

Use function could be thought of as try with resource in Java.

Syntax of Kotlin Use function

The syntax of use function is

inline fun <T : Closeable?, R> T.use(block: (T) -> R): R (source)

where

  • block is the function to process the Closeable resource.
  • fun returns the result of block function.
ADVERTISEMENT

Example 1 – Kotlin Use function

In this example, we will call use function on BufferedReader().

Kotlin Program – example.kt

import java.io.File

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

contents.txt is in input folder which is next to UseFunctionExample.kt

Output

Good Day !
Welcome to Kotlin Tutorials by www.tutorialkart.com.

Process finished with exit code 0

Conclusion

In this Kotlin Tutorial – Kotlin Use Function, we have learnt to use given block function on a resource.