5

In Java (or Python or other languages) one can pass a map of arguments to a function as a single parameter which is then 'expanded' and passed as individual arguments. Usually it consists of a special syntax, Python is foo (**oArgumentMap) in Java foo(Object... arguments);

Does something like this exist in Apex? One work around I can think is having a method with a signature that accepts a <String,Object>?

7

Short answer, no.

However, you could emulate it by passing a List<Object> instead.

void vargs(String s, List<Object> args) {
    // Do things
}

vargs('A string', new List<Object> { arg1, arg2, arg3 });
  • 1
    It could be argued that its essentially a "wrapper class". – crmprogdev Aug 5 '15 at 22:01
4

Another workaround design pattern that also future proofs your methods, and as an alternative to overloading and to workaround SF not letting you change global method signatures in managed packages is:

global void mFooBar(Map<String,Object> oArgumentMap) {
    System.debug(LoggingLevel.INFO, 'oArgumentMap: ' + oArgumentMap);
}
mFooBar(new Map<String,Object>{
    'number' => 1 
    ,'string' => 'hello'
    ,'object' => new List<Integer>()
});

Outputs:

oArgumentMap: {number=1, object=(), string=hello}

You may notice this approach is similar to the functionality introduced by the System.Callable in Winter '19 release.

  • This would be very error prone if you decided to refactor parameter names. It might be better to declare an object/class with members instead. Thus, you create an object parameter. – Kimball Robinson Mar 29 at 23:31
  • I've coded in both approaches and the class as parameter approach is crap to work with and more so when dealing with managed packages, and actually I don't see how refactoring the class as parameter object approach and any code depended on it less painful... – Daniel Sokolowski Mar 31 at 22:32
-1

I would strongly recommend against using a map, since you must go to extra trouble if the keys need to change names, and it's hard to find all usages of a parameter with your IDE, harder to debug, etc.

Instead, declare an object you'd like to pass around.

public class YourOuterClass {
        public void complexFunction(YourParameterObject params) {
        }

        public void usesAboveFunction() {
            complexFunction(new YourParameterObject(1, 'hello', someList)
        }

        public class YourParameterObject {
            // constructors and private members here.
        }
}

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.