Groovy, "try-with-resources" construction alternative

Groovy 2.3 also has withCloseable which will work on anything that implements Closeable

Groovy 3 newsflash

And Groovy 3+ supports try..with..resources as Java does

https://groovy-lang.org/releasenotes/groovy-3.0.html#_arm_try_with_resources


Simplest try-with-resources for all Groovy versions is the following (even works with AutoCloseable interface). Where class Thing is a closeable class or implements AutoCloseable.

new Thing().with { res ->
    try {
        // do stuff with res here
    } finally {
        res.close()
    }
}

Which is the equivalent in later versions of Groovy doing:

new Thing().withCloseable { res ->
    // do stuff with res here
}

Have a look at the docs on Groovy IO and the associated javadoc. It presents the withStream, withWriter, withReader constructions which are means of getting streams with auto-closeability

Tags:

Groovy