我有一个像这样的方法
def uploadFile(String fileName, boolean performCleanup = false) {
//upload file
if (performCleanup == true) {
//delete local file
}
}
我用两种方式调用此方法:
uploadFile("/some/path/to/file.txt")
uploadFile("/some/path/to/file.txt", true)
在第二种情况下,为了更好的可读性,我想传递一个变量名称,该名称表明传递true
的重要性。
类似于uploadFile("/some/path/to/file.txt", performCleanup: true")
这可能吗?
答案 0 :(得分:2)
您可以使用Map
来模拟命名的args:
def uploadFile(Map args) {
String fileName = args.fileName
// will default to false if omitted
boolean performCleanup = args.performCleanup
//upload file
if (performCleanup == true) {
//delete local file
}
}
然后,您可以使用
调用该方法uploadFile(fileName: "/some/path/to/file.txt")
uploadFile(fileName: "/some/path/to/file.txt", performCleanup: true)
与更典型的风格(其中每个值作为单独的参数传递)相比,这种风格有一些优点和缺点:
答案 1 :(得分:2)
通过引入和额外的闭包,您可以创建一个可读性很好的微型DSL:
def performCleanup = {
println "cleanup $it" //delete local file
}
def upload(fileName) {
println "upload file $fileName" //upload file
[then: { action ->
action(fileName)
}]
}
upload "path"
upload "path" then performCleanup
答案 2 :(得分:0)
我想建议另一种方式以DSL-ish的方式使用它,方法是返回一个可以响应performCleanup
的地图:
def uploadFile(String fileName) {
//upload file
println "uploading file"
[performCleanup: {
//delete local file
println "cleaning up"
}]
}
uploadFile 'file' performCleanup()
输出:
$ groovy Clean.groovy
uploading file
cleaning up
以后不调用performCleanup()
,它不会发生:
uploadFile 'file'
输出:
$ groovy Clean.groovy
uploading file