Last active
April 6, 2019 14:07
-
-
Save peterknolle/bae492d334800df6c58378fc24427c01 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Everything is pass by value in Apex. | |
* When a method is called the runtime pushes a stackframe on the stack and params | |
* are created as local vars, including ref vars. | |
* The object that the ref var points to lives on the heap and can be modified if not immutable. | |
* The param itself is the ref var and is by value like all params in Apex. | |
*/ | |
public class A { | |
public String val { get; set; } | |
} | |
void aMethod(A refVar) { | |
refVar = null; | |
System.debug('var in meth =' + refVar); | |
} | |
A refVar = new A(); | |
refVar.val = 'a'; | |
System.debug('before call = ' + refVar); | |
aMethod(refVar); | |
System.debug(refVar); | |
//Output | |
// 'before call = a' | |
// 'var in meth = null' | |
// 'a' -- sill 'a', because the modification in aMethod doesn't stick, because the parameter is pass by value. | |
//------------------------------------------------------------------------------------ | |
// Here's one that is a bit more explicit. It shows the param getting changed to | |
// another object in the method and it still does not persist. | |
//------------------------------------------------------------------------------------ | |
public class A { | |
public String val { get; set; } | |
} | |
void aMethod(A refVar) { | |
refVar = new A(); | |
refVar.val = 'b'; | |
System.debug('var in meth = ' + refVar); | |
} | |
A refVar = new A(); | |
refVar.val = 'a'; | |
System.debug('before call = ' + refVar); | |
aMethod(refVar); | |
System.debug(refVar); | |
//Output | |
// 'before call = a' | |
// 'var in meth = b' | |
// 'a' -- sill 'a', because the modification in aMethod doesn't stick, because the parameter is pass by value. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment