There is a use function in kotlin-stdlib (src).

How to use it:

OutputStreamWriter(r.getOutputStream()).use {
    // `it` is your OutputStreamWriter
    it.write('a')
}
Answer from user2235698 on Stack Overflow
Top answer
1 of 5
310

There is a use function in kotlin-stdlib (src).

How to use it:

OutputStreamWriter(r.getOutputStream()).use {
    // `it` is your OutputStreamWriter
    it.write('a')
}
2 of 5
82

TL;DR: No special syntax, just a function

Kotlin, as opposed to Java, does not have a special syntax for this. Instead, try-with-resources, is offered as the standard library function use.

FileInputStream("filename").use { fis -> //or implicit `it`
   //use stream here
} 

The use implementations

@InlineOnly
public inline fun <T : Closeable?, R> T.use(block: (T) -> R): R {
    var closed = false
    try {
        return block(this)
    } catch (e: Exception) {
        closed = true
        try {
            this?.close()
        } catch (closeException: Exception) {
        }
        throw e
    } finally {
        if (!closed) {
            this?.close()
        }
    }
}

This function is defined as a generic extension on all Closeable? types. Closeable is Java's interface that allows try-with-resources as of Java SE7.
The function takes a function literal block which gets executed in a try. Same as with try-with-resources in Java, the Closeable gets closed in a finally.

Also failures happening inside block lead to close executions, where possible exceptions are literally "suppressed" by just ignoring them. This is different from try-with-resources, because such exceptions can be requested in Java‘s solution.

How to use it

The use extension is available on any Closeable type, i.e. streams, readers and so on.

FileInputStream("filename").use {
   //use your stream by referring to `it` or explicitly give a name.
} 

The part in curly brackets is what becomes block in use (a lambda is passed as an argument here). After the block is done, you can be sure that FileInputStream has been closed.

🌐
Baeldung
baeldung.com › home › kotlin › kotlin basics › try-with-resources in kotlin
Try-with-resources in Kotlin | Baeldung on Kotlin
March 19, 2024 - Learn how Kotlin is managing resources automatically and how it differs from Java's try-with-resources construct.
Discussions

Concise way to manage resource with exception in kotlin - Language Design - Kotlin Discussions
Hi, new to kotlin here. I just stumble with managing resource with exception. When doing IO operation, IOException is just normal and expected (internet connection closed suddenly, disk full, etc), so it must caught and properly handled. In Java we can use try with resource to make a method ... More on discuss.kotlinlang.org
🌐 discuss.kotlinlang.org
0
December 1, 2017
Try-with-resources: the Kotlin way? - Kotlin Discussions
I must admit I quite like try-with-resources which was introduced in Java 7. I tried to find what the Kotlin way is, but with just little success, nevertheless I found an article on this topic: http://blog.jonnyzzz.name/… More on discuss.kotlinlang.org
🌐 discuss.kotlinlang.org
0
November 15, 2014
Try-with-resources or use() - Kotlin Discussions
try-with-resources and the Kotlin subsitute use() were mentioned in an older discussion. The link to the use() functions leads to nowhere. So what is the Kotlin solution for try-with-resources today? More on discuss.kotlinlang.org
🌐 discuss.kotlinlang.org
1
September 23, 2014
[SOLVED] Try with resources with `AutoClosable` - Support - Kotlin Discussions
Graph().use { .... } When I look into it, it appears that use requires a Closeable and does not work with an AutoClosable and AutoClosable does not inherit from Closable and is only available in JDK7 and up. Is there another way around this? I just noticed this from Kotlin needs try-with-resources ... More on discuss.kotlinlang.org
🌐 discuss.kotlinlang.org
0
May 15, 2017
🌐
Kotlin Discussions
discuss.kotlinlang.org › language design
Kotlin needs try-with-resources - Language Design - Kotlin Discussions
July 5, 2015 - Here are the problems with the ... is. In fact, you probably need to version the stdlib (and, perhaps, Kotlin itself) together with the JDK.) * Awkward to handle multiple resources * Often needs a try block anyway to catch the exceptions coming from close(), the constructor, ...
🌐
Kotlin Discussions
discuss.kotlinlang.org › language design
Concise way to manage resource with exception in kotlin - Language Design - Kotlin Discussions
December 1, 2017 - When doing IO operation, IOException ... In Java we can use try with resource to make a method never throw IOException and resource will properly closed when the method return....
🌐
Kotlin Discussions
discuss.kotlinlang.org › t › try-with-resources-the-kotlin-way › 404
Try-with-resources: the Kotlin way? - Kotlin Discussions
November 15, 2014 - I must admit I quite like try-with-resources which was introduced in Java 7. I tried to find what the Kotlin way is, but with just little success, nevertheless I found an article on this topic: http://blog.jonnyzzz.name/…
🌐
Medium
medium.com › @mkcode0323 › simplify-resource-handling-in-android-with-try-with-resources-and-kotlin-d2a554b483b4
Simplify Resource Handling in Android with Try-With-Resources and Kotlin | by KmDev | Medium
June 7, 2023 - Conclusion: Try-With-Resources is a powerful feature in Java and Kotlin that simplifies resource management in Android development. By leveraging this mechanism, you can avoid resource leaks, write cleaner code, and handle exceptions more ...
🌐
Kotlin Discussions
discuss.kotlinlang.org › language design
Kotlin needs try-with-resources - Page 2 - Language Design - Kotlin Discussions
July 31, 2017 - I agree with both of you, the + overload was bad and I’ve switched it out for a standard extension method, .autoClose(). Due to the overhead of the ResourceManager, and the messiness of requiring the finally {} block else all exceptions would be eaten (which is what people would inevitably do), I stand by my position that this is too important to just be a library function.
🌐
EDUCBA
educba.com › home › software development › software development tutorials › kotlin tutorial › kotlin try-with-resources
Kotlin try-with-resources | Kotlin try-with-resources Management
December 12, 2022 - Basically in kotlin try with resources is a try statement which was used to declare one or more resources. A resource is nothing but an object which was closed once in our program is done by using it.
Address   Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
Find elsewhere
🌐
TutorialsPoint
tutorialspoint.com › try-with-resources-in-kotlin
Try-with-resources in Kotlin
November 23, 2021 - As per Kotlin documentation, use() is defined as a generic extension on all closeable types. The implementation looks like this − ... 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. In this example, we will see how to use the use() function in order to implement try-with-resources.
🌐
Kotlin Discussions
discuss.kotlinlang.org › t › try-with-resources-or-use › 460
Try-with-resources or use() - Kotlin Discussions
September 23, 2014 - try-with-resources and the Kotlin subsitute use() were mentioned in an older discussion. The link to the use() functions leads to nowhere. So what is the Kotlin solution for try-with-resources today?
🌐
Techkluster
techkluster.com › kotlin › try-with-resources
Exploring Try-with-resources in Kotlin – TechKluster
Try for free · Kotlin · [email protected] August 29, 2023 · Previous Post Modifying Kotlin Lists In-Place · Next Post Kotlin-Java Interoperability: Bridging the Gap · Technology · November 27, 2025 · Kafka is widely used message broker especially in distributed systems, many ask this ...
🌐
Medium
appmattus.medium.com › effective-kotlin-item-9-prefer-try-with-resources-to-try-finally-aec8c202c30a
Effective Kotlin: Item 9 — Prefer try-with-resources to try-finally | by Matthew Dolan | Medium
October 29, 2021 - One of the reasons item 9 of Joshua Bloch’s book, Effective Java, suggests try-with-resources as a winner is when dealing with multiple resources the ensuing nest of try-finally blocks becomes ever harder to read. As discussed in item 8, Kotlin doesn’t have try-with-resources.
🌐
GitHub
github.com › DenWav › kotlin-try-with-resources
GitHub - DenWav/kotlin-try-with-resources · GitHub
Kotlin has no answer to Java's try-with-resources mechanic. This is sad as it's probably the only thing Java has that Kotlin doesn't. Kotlin's response is with the AutoCloseable#use() extension method.
Starred by 10 users
Forked by 2 users
Languages   Kotlin
🌐
Kotlin Discussions
discuss.kotlinlang.org › support
[SOLVED] Try with resources with `AutoClosable` - Support - Kotlin Discussions
May 15, 2017 - I’m using TensorFlow which provides public final class Graph implements AutoCloseable However I am getting an error when I try to use the try-with-resources construct of Kotlin like this… Graph().use { .... } When I look into it, it appears that use requires a Closeable and does not work with an AutoClosable and AutoClosable does not inherit from Closable and is only available in JDK7 and up.
🌐
Joao Alves
joaoalves.dev › posts › kotlin-playground › kotlin-trywithresources-use
Kotlin try-with-resources — use - Joao Alves
March 12, 2020 - It also handles all possible exceptions including possible exception while closing the resource. Note: As suggested by Simon in the comments, it’s worth mentioning that from Java 7 onwards we can also use try-with-resources and get resources automatically closed, since they also implement AutoCloseable from that version.
Top answer
1 of 6
13

There is no standard solution for this. If you had all of the Closable instances ready at the start, you could use your own self-defined methods to handle them, like this blog post or this repository shows (and here is the discussion on the official forums that led to the latter).

In your case however, where subsequent objects rely on the previous ones, none of these apply like a regular try-with-resources would.

The only thing I can suggest is trying to define helper functions for yourself that hide the nested use calls, and immediately place you in the second/third/nth layer of these resourcs acquisitions, if that's at all possible.

2 of 6
6

For simplicity I will use A,B and C for the chained autocloseables.

import java.io.Closeable

open class MockCloseable: Closeable {
    override fun close() = TODO("Just for compilation")
}
class A: MockCloseable(){
    fun makeB(): B = TODO()
}
class B: MockCloseable(){
    fun makeC(): C = TODO()

}
class C: MockCloseable()

Using uses

This would look like this:

A().use {a ->
    a.makeB().use {b -> 
        b.makeC().use {c -> 
            println(c)
        }
    }
}

Making a chain use function with a wrapper

Definition

class ChainedCloseable<T: Closeable>(val payload: T, val parents: List<Closeable>) {
    fun <U> use(block: (T)->U): U {
        try {
            return block(payload)
        } finally {
            payload.close()
            parents.asReversed().forEach { it.close() }
        }
    }

    fun <U: Closeable> convert(block: (T)->U): ChainedCloseable<U> {
        val newPayload = block(payload)
        return ChainedCloseable(newPayload, parents + payload)
    }
}

fun <T: Closeable, U: Closeable> T.convert(block:(T)->U): ChainedCloseable<U> {
    val new = block(this)

}

Usage

A()
    .convert(A::makeB)
    .convert(B::makeC)
    .use { c ->
         println(c)
    }

This allows you to avoid having to nest deeply, at the cost of creating wrapper objects.

🌐
DaniWeb
daniweb.com › programming › software-development › tutorials › 536464 › kotlin-equivalence-of-java-try-with-resource-statement
Kotlin equivalence of Java try-with-resource ... | DaniWeb
We did not have to call close() manually because the try-with-resource statement will automatically do that for us. Kotlin actually does not have a language construct like try-with-resource.
🌐
Reddit
reddit.com › r/kotlin › the "use" keyword for multiple resources
r/Kotlin on Reddit: the "use" keyword for multiple resources
March 24, 2023 -

Is there way to write the following but without all the nasty nested brackets?

fun main() {
    val file1 = File("file1.txt")
    val file2 = File("file2.txt")

    file1.inputStream().use { stream1 ->
        file2.inputStream().use { stream2 ->
            BufferedReader(InputStreamReader(stream1)).use { reader1 ->
                BufferedReader(InputStreamReader(stream2)).use { reader2 ->
                    // Use the file readers here
                    val line1 = reader1.readLine()
                    val line2 = reader2.readLine()
                    println("Line 1 from ${file1.name}: $line1")
                    println("Line 1 from ${file2.name}: $line2")
                }
            }
        }
    }
}

Like in C#?

class Program {
    static void Main(string[] args) {
        string file1 = "file1.txt";
        string file2 = "file2.txt";

        using (var stream1 = new FileStream(file1, FileMode.Open))
        using (var stream2 = new FileStream(file2, FileMode.Open))
        using (var reader1 = new StreamReader(stream1))
        using (var reader2 = new StreamReader(stream2)) {
            // Use the file readers here
            string line1 = reader1.ReadLine();
            string line2 = reader2.ReadLine();
            Console.WriteLine("Line 1 from {0}: {1}", file1, line1);
            Console.WriteLine("Line 1 from {0}: {1}", file2, line2);
        }
    }
}

thanks

Top answer
1 of 5
37
Use isn't a keyword in Kotlin. It's an inline function . As such, you could have built it yourself, or you can make a different version of it. You could, for example, implement a function with this signature (completely untested): inline fun use2( f1: () -> T1, f2: () -> T2, block: (T1, T2) -> R ): R { return f1().use { v1 -> f2().use { v2 -> block(v1, v2) } } } And call it like this: use2( { file1.inputStream() }, { file2.inputStream() } ) { stream1, stream2 -> ... } You want f1 and f2 to be functions, not simple values, because you want to clean up the value produced by f1 if the f2 function were to throw. That is, this implementation would not be good: inline fun use2( v1: T1, v2: T2, block: (T1, T2) -> R ): R { return v1.use { v2.use { block(v1, v2) } } } use2( file1.inputStream(), file2.inputStream() ) { stream1, stream2 -> ... } Because file1.inputStream() and file2.inputStream() are evaluated before the inline function gets called, so if file2.inputStream() throws, then the file1 InputStream won't get cleaned up. You could be clever and support larger numbers of parameters by re-using this implementation: inline fun use3( f1: () -> T1, f2: () -> T2, f3: () -> T3, block: (T1, T2, T3) -> R ): R { return use2(f1, f2) { v1, v2 -> f3().use { v3 -> block(v1, v2, v3) } } } As far as I know, you need to manually create these variations. There's no type-safe way in Kotlin to support an arbitrary number of such parameters. It's clunky, but maybe less clunky than deeply-nested blocks.
2 of 5
34
u/balefrost 's answer is awesome and worth considering first. But if you wanted something that somewhat emulated the C# case, you could create a ClosableScope class and closableScope utility method: class CloseableScope { private val closeables = mutableListOf() fun using(closeable: T): T { closeables.add(closeable) return closeable } internal fun closeAll() { // Close in the opposite order we opened them in closeables.reversed().forEach { it.close() } // IMPORTANT NOTE ABOUT THIS CODE, SEE BELOW (†) } } fun closeableScope(block: CloseableScope.() -> Unit) { val cs = CloseableScope() try { cs.block() } finally { cs.closeAll() } } fun main() { closeableScope { val file1 = File("file1.txt") val file2 = File("file2.txt") val stream1 = using(file1.inputStream()) val stream2 = using(file2.inputStream()) val reader1 = using(stream1.bufferedReader()) val reader2 = using(stream2.bufferedReader()) // Use reader1 and reader2 here } } † IMPORTANT NOTE: In a real codebase, the closeAll method should also protect against it.close throwing, which can be tricky because you'll potentially need to accumulate multiple exceptions thrown in a row. Check out one user's proper implementation here (which they wrote in response to this reddit thread): https://github.com/Black-Kamelia/Sprinkler/blob/binary-serializers/util/src/main/kotlin/com/kamelia/sprinkler/util/closeable/CloseableScope.kt
🌐
Kotlin Discussions
discuss.kotlinlang.org › t › try-with-resources-the-kotlin-way › 404 › 3
Try-with-resources: the Kotlin way? - #3 by pdolezal - Kotlin Discussions
November 21, 2014 - I must admit I quite like try-with-resources which was introduced in Java 7. I tried to find what the Kotlin way is, but with just little success, nevertheless I found an article on this topic: http://blog.jonnyzzz.name/…
🌐
Skillapp
skillapp.co › blog › mastering-kotlins-try-with-resources-a-comprehensive-guide-for-effortless-resource-management
Mastering Kotlin’s Try with Resources – A Comprehensive Guide for Effortless Resource Management
Try with resources is a language construct that allows us to declare and use resources inside a try block, and the resources are automatically closed when the block is exited. Its purpose is to ensure that resources are properly released, even in the presence of exceptions.