Passing a variable number of arguments to Apex class methods

In a method in apex class, is it possible to give variable number of arguments.
method1(arg1,arg2,...)
Will this be working fine ??

Answer

Unfortunatley this isn’t possible. You can overload methods, so if there’s only ever going to be 2, 3 or 4 arguments say, you could do:

void method1(String arg1, String arg2)
{
  method1(arg1, arg2, '', '');
}

void method1(String arg1, String arg2, String arg3)
{
  method1(arg1, arg2, arg3, '');
}

void method1(String arg1, String arg2, String arg3, String arg4)
{
  // do stuff
}

Alternatively, assuming your arguments are all of the same type (which seems likely in such a use case), you could just use a list:

void method1(List<String> args)
{
}

Even if they’re different types you could cast to strings to put in the list, or use List<Object>; but that could get messy and it depends on what it is you’re doing.

Attribution
Source : Link , Question Author : Apexist , Answer Author : Matt Lacey

Leave a Comment