Skip to content

Instantly share code, notes, and snippets.

@int128
Created June 6, 2016 12:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save int128/a136eb262b8f3f8decfda23542645b77 to your computer and use it in GitHub Desktop.
Save int128/a136eb262b8f3f8decfda23542645b77 to your computer and use it in GitHub Desktop.
Handling varargs and closure in Groovy
def execute(... arguments) {
if (arguments.head() instanceof Map) {
def settings = arguments.head()
if (arguments.last() instanceof Closure) {
def callback = arguments.last()
def commandArgs = arguments[1..(arguments.length - 2)]
println([commandArgs, settings, callback])
} else {
def commandArgs = arguments[1..(arguments.length - 1)]
println([commandArgs, settings])
}
} else {
if (arguments.last() instanceof Closure) {
def callback = arguments.last()
def commandArgs = arguments[0..(arguments.length - 2)]
println([commandArgs, callback])
} else {
def commandArgs = arguments[0..(arguments.length - 1)]
println commandArgs
}
}
}
execute()
execute 'abc'
execute 'abc', pty: true
​execute('abc', pty: true) {}
execute 'abc', 'def'
execute 'abc', 'def', pty: true
execute('abc', 'def', pty: true) {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment