- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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".
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)
- Related Articles
- How to use try-with-resources with JDBC?
- How to declare multiple resources in a try-with-resources statement in Java 9?
- Effectively final variables in try-with-resources in Java 9?
- What are the improvements for try-with-resources in Java 9?\n
- How to read a text file from resources in Kotlin?
- What is try-with-resource in java?
- Explain try and catch statements in JavaScript with examples.
- try keyword in C#
- PHP Resources
- Can we define a try block with multiple catch blocks in Java?
- Try-Catch-Finally in C#
- try and except in Python
- How to work with Maps in Kotlin?
- People Natural Resources
- People as Resources
