Over a million developers have joined DZone.

Groovy Goodness: More Efficient Tail Recursion With TailRecursive Annotation

· Java Zone

Learn more about the advantages of moving from a monolithic to microservices architecture.  Brought to you in partnership with IBM.

Since Groovy 1.8 we can use the trampoline method for a closure to get better recursive behavior for tail recursion. All closure invocations are then invoked sequentially instead of stacked, so there is no StackOverFlowError. As from Groovy 2.3 we can use this for recursive methods as well with the @TailRecursive AST transformation. If we apply the annotation to our method with tail recursion the method invocations will be sequential and not stacked, like with the closure's trampoline method.

import groovy.transform.TailRecursive

long sizeOfList(list, counter = 0) {
    if (list.size() == 0) {
    } else {
       sizeOfList(list.tail(), counter + 1) 

// Without @TailRecursive a StackOverFlowError
// is thrown.
assert sizeOfList(1..10000) == 10000

Code written with Groovy 2.3.

From Idea to Application gives you the architecture to quickly build, manage and run a range of applications (web, mobile, big data, new smart devices, etc.) on an open-standard, cloud-based platform. See why developers are using IBM Bluemix. Brought to you in partnership with IBM.


Published at DZone with permission of Hubert Klein Ikkink, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

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.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}