use Function for Resources in Kotlin
On this page (12sections)
Introduction
use Function for Resources is a fundamental concept every Kotlin developer should understand. File I/O reads and writes persistent data on disk. Kotlin wraps Java file APIs with extension functions for cleaner syntax.
The use extension closes Closeable resources automatically, even when exceptions occur. In this tutorial you will learn the syntax, walk through a complete example program, study the sample output, and review best practices so you can apply the concept confidently in your own projects.
Definition
- The use extension closes Closeable resources automatically, even when exceptions occur.
- It is Kotlin’s equivalent of Java’s try-with-resources.
- Always prefer use when working with files, streams, and database connections.
Syntax
File("data.txt").bufferedReader().use { reader ->
reader.readLine()
}
use Function for Resources in Kotlin Example Program in Kotlin
import java.io.File
fun main() {
val file = File("sample.txt")
file.writeText("Line 1
Line 2")
file.bufferedReader().use { reader ->
reader.forEachLine { line -> println(line) }
}
file.delete()
}
Sample Output
Line 1
Line 2
When to use
Use file I/O for reading config files, writing logs, or processing CSV/JSON stored on disk.
How it works
-
The program starts with a
mainfunction — the entry point that runs when you execute the file. -
The use extension closes Closeable resources automatically, even when exceptions occur.
-
Run the program in IntelliJ IDEA, Android Studio, or with the Kotlin command-line compiler (
kotlinc/kotlin). Compare your console output with the sample output shown below.
Best Practices
- Understand the core idea: the use extension closes Closeable resources automatically, even when exceptions occur.
- Prefer readable names and small functions so examples map directly to real projects.
- Run and modify the example — change values and observe how the output changes.
Common Mistakes
- Skipping the example and only reading the definition — hands-on practice cements the concept.
- Copying syntax without understanding nullable vs non-nullable types or scope rules.
- Ignoring compiler warnings that often point to safer alternatives.
Key Points
- The use extension closes Closeable resources automatically, even when exceptions occur.
- It is Kotlin’s equivalent of Java’s try-with-resources.
- Always prefer use when working with files, streams, and database connections.
- Test the example locally and verify the output matches the sample.
- Experiment by changing input values to see how behaviour changes.
Notes
- This example creates a temporary file in the working directory and deletes it at the end.
- File examples assume a writable working directory; adjust paths for your environment.