function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Sam MohyeeSam Mohyee 

Correctly passing lists by reference for a recursive function

Hi,

 

I'm writing a recursive method to discover all the child accounts for a given parent account (at all levels, not just immediate children).

 

My code right now:

 

    //Recursively goes through child accounts and adds to ID_Group list.
    public static List<ID> Get_Children(ID mainID, List<ID> ID_Group){        
        for(Account child :[SELECT ID, ParentID FROM Account WHERE ParentID = :mainID]){
            if(child.ParentId == mainID){ /*IF clause to make sure SOQL returned an actual account*/
                ID_Group.add(child.id);
            	Get_Children(child.id, ID_Group);
            }
        }
return ID_Group; }

 

Basically, the function is passed a list of IDs whose first element is the 'main' or starting ID, from which we want to find all children account (for my larger program I happen to separate out the first element and pass it as a separate variable than the list itself).

 

You can see that as the for loop iterates through all the immediate children, their IDs are added to the main list, and then a recursive branch is created to go through all the children of each of those children, and so on. 

 

The issue I have right now is with the return clause - after all, isn't it true that as written this function will return an ID_Group list for EACH branch of the recursion? I wish for the function to finish all its recursive branches, add all the children IDs to the list, and THEN return the list when there are no more recursions.

 

I thought I might do that by passing a reference to the list, so the list can be populated by the method and not have to be returned afterward (ie, I would just be able to reference the list variable in another method later, and it would still be populated from this recursive method). 

 

How could I accomplish this? I understand passing by reference in APEX/java is different than in C, and may not get me what I want.