Search code examples
groovytry-with-resources

Groovy multiple resource closure


I'm using the resource closure feature of Groovy, and was wondering if it was possible to create one closure that manages two resources. For example, if I have the following two separate closures, is it possible to create one closure that manages both? Or do I really have to nest the closures?

new File(baseDir, 'haiku.txt').withWriter('utf-8') { writer ->
    writer.writeLine 'Into the ancient pond'
}

new Scanner(System.in).with { consoleInput ->
    println consoleInput.nextLine()
}

Solution

  • No. The syntax method(arg) {} is an alternative syntax to method(arg, {}), thus, you can do this:

    fn = { writer ->
        writer.writeLine 'Into the ancient pond'
    }
    
    new File(baseDir, 'haiku.txt').withWriter('utf-8', fn) 
    
    new Scanner(System.in).with(fn)
    

    Note that the closure must contain expected code for both method invocations.