Groovy, "try-with-resources" construction alternative

Groovy

Groovy Problem Overview


I'm a new to Groovy. I used to use 'try-with-resources' construction in my Java code during work with I/O streams.

Could you please advise, is there any analogue of such construction in Groovy?

Groovy Solutions


Solution 1 - Groovy

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

Solution 2 - Groovy

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

Solution 3 - Groovy

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
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionXZenView Question on Stackoverflow
Solution 1 - Groovytim_yatesView Answer on Stackoverflow
Solution 2 - GroovyGrooveekView Answer on Stackoverflow
Solution 3 - GroovySam GleskeView Answer on Stackoverflow