2017-07-03 124 views
1

我正在使用Groovy的資源關閉功能,並想知道是否可以創建一個管理兩個資源的閉包。例如,如果我有以下兩個單獨的閉包,是否可以創建一個管理兩個閉包的閉包?或者我真的必須嵌套關閉?Groovy多重資源關閉

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

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

也許這個鏈接可以幫助你嗎? https://stackoverflow.com/questions/23382079/groovy-try-with-resources-construction-analogue – rafaelim

回答

0

號的語法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) 

注意,關閉必須包含預期代碼兩種方法調用。