Over a million developers have joined DZone.

Closure Composition in Groovy

· Java Zone

Microservices! They are everywhere, or at least, the term is. When should you use a microservice architecture? What factors should be considered when making that decision? Do the benefits outweigh the costs? Why is everyone so excited about them, anyway?  Brought to you in partnership with IBM.

This is a short blog post about a feature of Groovy closures I discovered a few days ago: Closure Composition.

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 >> square

If we now call c() first half() will be called. The return value of half() will then be passed toplusOne(). At last square() will be called with the return value of plusOne().

println c(10) // (10 / 2 + 1)² -> 36

We can reverse the call order by using the << operator instead of >>

def c = half << plusOne << square

Now square() will be called before plusOne(). half() will be called last.

println c(10) // (10² + 1) / 2 -> 50.5


Discover how the Watson team is further developing SDKs in Java, Node.js, Python, iOS, and Android to access these services and make programming easy. Brought to you in partnership with IBM.

Topics:

Published at DZone with permission of Michael Scharhag, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}