Pass by Value or Pass by Reference in Salesforce
Pass by Value:
When you pass a primitive data type (such as Integer, Boolean, String) as an argument to a method, a copy of the value is passed to the method.
Any changes made to the parameter within the method do not affect the original value of the variable passed in.
This behavior is consistent with most programming languages and is commonly referred to as pass-by value.
Example:
public void incrementValue(Integer x) {x++; // Changes made to 'x' do not affect the original value of the variable passed in
}
Integer value = 10;
incrementValue(value);
System.debug(value); // Output: 10 (unchanged)
Pass by Reference (for non-primitive data types):
When you pass a non-primitive data type (such as List, Map, Set, or custom objects) as an argument to a method, a reference to the original variable is passed to the method.
This means that changes made to the parameter within the method can affect the original value of the variable passed in.
However, assigning a new value to the parameter variable itself (e.g., list = new List<Integer>();) does not affect the original variable passed in.
Example:
public void addToList(List<Integer> list) {
list.add(20); // Changes made to 'list' affect the original variable passed in
}
List<Integer> numbers = new List<Integer>{10};
addToList(numbers);
System.debug(numbers); // Output: (10, 20)
While primitive data types are always passed by value, non-primitive data types are effectively passed by reference, allowing modifications to the data structure within the method to be reflected in the original variable.
Links
Comments
Post a Comment