title: Groovy recursive function where to store results?
body: <p>I am trying to build a simple tree like structure of objects and identify the depth level of each object. To do this i have created a recursive function but this function always returns the last results and not the expected total results. I probably store the results in a incorrect place. </p>
  
  <pre><code>def getStructure(anObject, level=0) {
  
      def results = []
  
      // [parent id, object id, level]
  
      if(anObject.parent == null) {
          results.add([0, anObject.id, level])
      } else {
          anObject.children?.each { child -&gt;
              results.add([anObject.parent.id, child.id, level])
      }
  
      // recursive call
      anObject.children?.each { child -&gt;
         getStructure(child, level++)
      }
  
      results
  }
  </code></pre>
  
  <p>In my test case i always get the latest run, so i guess the results = [] gets reinitialized every time. How do i store the results from a recursive function?</p>