Over a million developers have joined DZone.

Cool Stuff in Groovy 1.8: Trampoline

DZone's Guide to

Cool Stuff in Groovy 1.8: Trampoline

· Java Zone
Free Resource

Are you joining the containers revolution? Start leveraging container management using Platform9's ultimate guide to Kubernetes deployment.

Those who have experience with functional programming know how useful tail recursion is. It allows use to write recursive functions occupying only one stack frame for all their calls instead of taking a new frame for each call. Tail recursion is a feature that you’d rarely see in object-oriented languages and Groovy is not an exception. I’d rather say it used to be this way in an obsolete Groovy 1.7. All of us who are using a brand new Groovy 1.8 can enjoy a tail recursion substitute (not being an expert in functional programming I can’t say if it works in all cases, but it’d be interesting to look at an example where it won’t be sufficient).

Let’s take a look at this piece of code:

def factorial
factorial = {
    it <= 1 ? 1G : it * factorial(it - 1)
factorial(500G) //stack overflow

Stack overflow is what you will get trying to execute this piece of code. What we can do in Groovy 1.8 to make it work is to use the trampoline method:

def factorial
factorial = {it, acc = 1->
    it <= 1 ? acc : factorial.trampoline(it - 1, it * acc)

factorial(500G) //no stack overflow

The trampoline method wraps our closure into a TrampolineClosure object. Groovy executes all factorial.trampoline(..) calls sequentially until our closure returns something else than an instance of TrampolineClosure. This is amazing how useful and, at the same time, simple it is.

From http://victorsavkin.com/post/5231079655/cool-stuff-in-groovy-1-8-trampoline

Moving towards a private or Hybrid cloud infrastructure model? Get started with our OpenStack Deployment Models guide to learn the proper deployment model for your organization.


Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

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


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

{{ parent.tldr }}

{{ parent.urlSource.name }}