Groovy, "try-with-resources" construction alternative

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?


Solution 1:

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:

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:

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
}