Apex - Pass by Value and Pass by Reference

“In Apex, all primitive data type arguments, such as Integer or String, are passed into methods by value. This means that any changes to the arguments exist only within the scope of the method. When the method returns, the changes to the arguments are lost.
Non-primitive data type arguments, such as sObjects, are also passed into methods by value. This means that when the method returns, the passed-in argument still references the same object as before the method call, and can’t be changed to point to another object. However, the values of the object’s fields can be changed in the method.”


The key takeaway for non-primitive data type arguments like Lists, Maps, sObjects etc is: when these variables are passed to methods, and the sObject's fields (or List's elements) are updated in the method, the updated values are retained when the method returns. 

Read below posts for detailed explanation with code examples.

This blog post by Josh Kaplan details about passing parameters By Reference and By Value in Apex.
https://developer.salesforce.com/blogs/developer-relations/2012/05/passing-parameters-by-reference-and-by-value-in-apex.html

This works in the same way as Java, here is a post explaining pass by reference in Java. 
https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value/7034719#7034719

0 comments:

Post a Comment