Kotlin Use function

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

Following is the syntax of use function

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

block is the function to process the Closeable resource.

fun returns the result of block function.

 

Example of Kotlin Use function

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

 

Conclusion :

In this Kotlin Tutorial, we have learnt to use Kotlin Function on a resource.