2

From the documentation:

        Passing Method Arguments By Value
   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.

Example:

class A {

    x=1;

    B.setx(x);

 --here i want x=2---
}

class B{
   public setx(int x){
     x=2;
   }
}

How can i pass a primitive value to a function by reference?

Thanks in advantage for any advice.

3
  • 1
    Can you make your example clearer as to why you need this capability? Also best to check that the code you post at least compiles before posting it (i.e class A). As objects are passed by reference, you can make your primitive a field of an object and pass that to a method and then the method can modify the primitive. Though that isn't typically an elegant way to organise your code.
    – Keith C
    Apr 9 '14 at 17:01
  • Thanks Keith! I´m sorry for the draft example. I want to export a big section of code of a class A, creating a function named "Utility" in class B. In class A i will call this method of class B. The problem is that there is a variable (integer value) that is setted in the portion that will be included in the method "Utility", later i will need the changed integer value in the class A (after executed the utility method ). Thanks a lot.
    – Enry
    Apr 9 '14 at 17:13
  • If it is just a single value that you want to return then your method can do that without any need for pass by reference public Integer utility(Integer x) { ...; return x * 2; }.
    – Keith C
    Apr 9 '14 at 17:38
1

As it states, primitives are passed by value. There is no syntax for passing references explicitly. Instead, pass a map or a wrapper class in:

Void increment(map<object, integer> values) {
    For(object key: values.keyset())
        Values.put(key, values.get(key)+1);
}

The results will be visible to the caller via the map.

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.