1

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()
}
kibowki
  • 4,206
  • 16
  • 48
  • 74
  • Maybe this link can help you? https://stackoverflow.com/questions/23382079/groovy-try-with-resources-construction-analogue – rafaelim Jul 04 '17 at 15:14

1 Answers1

0

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.

Will
  • 14,348
  • 1
  • 42
  • 44