-2

I have three methods:

Method1:

public static void method1() {

// call method 2 that returns a list
method2();

// call method 3 and pass list retuned from method 2
method3(myList);

}

Method 2:

private static list<objName> method2() {

List<objName> myList = new List<objName>();

// remaining code

return myList;

}

Method 3:

public static Map<x,y> method3(List<myObj> myList) {

// other code
}

My question is: inside method1, how can I pass the list that is returned from method2 into method3?

2

When you called the Method2 From Method 1, then it returns the List. After that the same list you can pass to Method3.

public static void method1() {

// call method 2 that returns a list
List<objname> theListReturnedFromMethod2 = method2();

// call method 3 and pass list retuned from method 2
method3(theListReturnedFromMethod2 );

}
1
  • will this execute the code inside method2?
    – MShal
    Aug 19 '21 at 11:45
0

I found the solution. Declare the list in Method1 and pass it as parameter to both Method2 and Method3.

Method 1:

public static void method1() {

List<myObj> myList = new List<myObj>();

method2(myList);

method3(myList);

}

Method 2:

public static List<myObj> method2(List<myObj> myList) {
    
// other code
return myList;
}
0

Storing the result of calling a method is the usual way to accomplish this.

List<String> myFirstResult = myMethod1();

List<String> mySecondResult = mySecondMethod(myFirstResult);

In many programming languages, including Apex, you can compose method calls.

That is, when you call one method, you can directly call another method in the arguments (provided that the return type of the second method is suitable).

myMethod(otherMethod())

In your case...

public static void method1() {
    // A method is only called after all of the arguments have been evaluated
    // So, method2() ends up being called first
    //   and then  method3() is called
    method3(method2());
}

Would be the minimum code required.

This approach is generally only suitable for methods with a short list of arguments. Otherwise, it tends to become hard to read.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.