+ Start a Discussion

Pass optional argument?

Don't have much experience with Java, but is there a way that I can specify optional parameters in my method?


An example in PHP would be...


function someFunction( $required, $optional = 'default_value' );


I'm assuming this can be done since with Batch Apex you can specify an optional scope between 0 - 200.


Apex is a strongly type language so we do not have optional method parameters. We employ method overloading in which you create a second version of the method with additional or different parameters.



In theory could you have 4 different overload methods in one class?
yes, this is very doable.

Optional arguments would be a great thing. I'm unsure why Apex's being strongly typed would preclude them.  Both C# and Java have them and both are strongly typed.


Where optional parameters would be especially useful would be the String.Format() static method.  Rather than requiring the programmer to stop what they're doing and create a string array so they may format it, it would be far preferable to simply accept variable arguments.


Much less code would be required to work-around a language limitation than is necessary now.


Inside our exception class we overloaded Raise() so that up to five arguments are supported:


public void Raise(string format, string arg1) {

  Raise(format, arg1, null);



public void Raise(string format, string arg1, string arg2) {

  Riase(format, arg1, arg2, null);



public void Raise(string format, string arg1, string arg2, string arg3) {

  Raise(format, arg1, arg2, arg3, null);



public void Raise(string format, string arg1, string arg2, string arg3, string arg4) {

  throw new ClientException(String.Format(format, new string[] { arg1, arg2, arg3, arg4 }));



The next improvment would be to allow arbitrary argument types so that integers, dates, and anything else that has a printable representation may be an argument, saving the programmer's converting values with String.ValueOf() for every non-string parameter.  If Apex is object-oriented and every object can be sent to String.ValueOf(), then it would be great to permit them.



Pablo, have you never used varargs?