简体   繁体   English

Groovy多资源关闭

[英]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. 我正在使用Groovy的资源关闭功能,想知道是否可以创建一个管理两个资源的关闭。 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()
}

No. The syntax method(arg) {} is an alternative syntax to method(arg, {}) , thus, you can do this: 否。语法method(arg) {}method(arg, {})的替代语法,因此,您可以这样做:

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. 请注意,闭包必须包含两个方法调用的预期代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM