7

How do you set a default value for a method input?

public void myMethod(String input1, String input2);

I would like to allow people to only need to state one of the inputs if they want (and have input2 default to a value

myMethod(myString); //Right now this fails because it doesn't match method(String, String)

2 Answers 2

10

In this case the best approach is going to be to overload the method, as Apex doesn't have any concept of optional parameters.

So to illustrate, your class might look like this:

public void myMethod(String input1, String input2) {
    System.debug(input1);
    System.debug(input2);
}

public void myMethod(String input1) {
    myMethod(input1, 'DEFAULT VALUE STRING');
}

You'll notice that both methods have exactly the same name, but the second method takes only 1 parameter, and then calls the original 2 parameter method putting a default value into parameter 2. In this way, you now have the option of calling the 2 parameter method if you need to, but can also call the simpler 1 parameter method with the same name

3
  • Makes sense and that is roughly what I did. I was just wondering (hoping) there was a better way! Sep 19, 2013 at 22:18
  • 1
    Oops...you beat me to the answer by a minute... Sep 19, 2013 at 22:19
  • 1
    Unfortunately not, Nathan! It would be nice to have optional/named params, but this is a nice robust pattern to get used to, and it's quite easily extensible. Just a PITA when you're used to the named params from Python, C# 10, etc, etc. Nathan's other suggestions are definitely worth a look too, but you should carefully consider the use cases for them; null based pattern can get quite cluttered when there are many optional params, and using a Map is susceptible to subtle bugs around misspelling keys and things like that.
    – James Hill
    Sep 19, 2013 at 22:23
2

Apex doesn't support dynamic parameters as in .NET. That said, there are couple of options with pros and cons with each approach.

  • Null: Just pass null from the calling code and in your callee code check for null and assign default value(s). For e.g.

    doProcess('test1', null); ... public void doProcess(String param1, String param2) { if(param2 == null) param2 = 'default';
    }

  • Map: Pass the values as a key/value pair in a map. Check the key and if it is null, then assign default answer.

  • Method overload: Provide method overloads and assign the default values in the method which has all the parameters and call this method from other method overloads.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .