Reputation: 35938
I have a method such as this
def uploadFile(String fileName, boolean performCleanup = false) {
//upload file
if (performCleanup == true) {
//delete local file
}
}
I call this method in two ways:
uploadFile("/some/path/to/file.txt")
uploadFile("/some/path/to/file.txt", true)
In the second case, for better readability, I would like to pass a variable name that would suggest what the significance of passing true
is.
Something like, uploadFile("/some/path/to/file.txt", performCleanup: true")
Is this possible?
Upvotes: 2
Views: 5752
Reputation: 14529
I'd like to suggest another way to use it in a DSL-ish way, by returning a map which can responds to performCleanup
:
def uploadFile(String fileName) {
//upload file
println "uploading file"
[performCleanup: {
//delete local file
println "cleaning up"
}]
}
uploadFile 'file' performCleanup()
Output:
$ groovy Clean.groovy
uploading file
cleaning up
By not calling performCleanup()
after, it doesn't happen:
uploadFile 'file'
Output:
$ groovy Clean.groovy
uploading file
Upvotes: 0
Reputation: 6977
By introducing and extra closure you can create a nicely readable micro 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
Upvotes: 3
Reputation: 187529
You can use a Map
to simulate named 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
}
}
You can then call the method using
uploadFile(fileName: "/some/path/to/file.txt")
uploadFile(fileName: "/some/path/to/file.txt", performCleanup: true)
This style has some pros and cons compared to the more typical style (wherein each value is passed as a separate argument):
Upvotes: 2