Skip to content

Instantly share code, notes, and snippets.

@timyates
Created February 14, 2012 12:28
Show Gist options
  • Select an option

  • Save timyates/1826452 to your computer and use it in GitHub Desktop.

Select an option

Save timyates/1826452 to your computer and use it in GitHub Desktop.
Concatenation of Closures in Groovy
// take a boolean evaluating closure, a result for truth and a result for false
def fn_if = { cond, tr, fa, Object... overflow ->
if( cond() ) [ tr, *overflow ] else [ fa, *overflow ]
}
// take two parameters, and return the result of multiplying these together
def fn_mult = { a, b, Object... overflow ->
[ a * b, *overflow ]
}
// Our input parameters
params = [ { 3 > 4 }, 'yay', 'boo', 2 ]
// Our concatenated function passes params to fn_if,
// and the result (plus any unused params) to fn_mult
def combinedFn = fn_mult << fn_if
// Call our concatenated closure
println combinedFn( *params )
// prints [ 'booboo' ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment