With Closure Composition we can chain closure calls within a single closure.
Assume we have the following three closures:
def square = { it * it } def plusOne = { it + 1 } def half = { it / 2 }Now we can combine those closures using the << or >> operators:
def c = half >> plusOne >> squareIf we now call c() first half() will be called. The return value of half() will then be passed to plusOne(). At last square() will be called with the return value of plusOne().
println c(10) // (10 / 2 + 1)² -> 36We can reverse the call order by using the << operator instead of >>
def c = half << plusOne << squareNow square() will be called before plusOne(). half() will be called last.
println c(10) // (10² + 1) / 2 -> 50.5
Leave a reply