Does APEX support variable arguments (`varargs` in Java`)

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 });

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.

Tags:

Apex