Define APEX method with default arguments

I am curious if APEX permits declaration of default arguments (or parameters if you will). When calling the method without specifying the value, method would be executed with the default value, otherwise with the value specified. I expect it would look somehow like this:

public String foo(String name, String greeting = 'Hello'){
    return greeting + ' ' + name;
}

Then calling this twice

foo('John');
foo('John', 'Good Evening');

would give me

Hello John
Good evening John

Is this somehow possible to do in APEX out of the box, or do I have to, for example, define overload for the method like this?

public String foo(String name){
    return foo(name, 'Hello');
}

public String foo(String name, String greeting){
    return greeting + ' ' + name;
}

Answer

In some use cases, you might want to consider fluent constructors on classes (or inner classes)

public class Foo {
  Integer bar = 0;  // default
  String  fie = 'Hello';

  public static Foo newInstance() {return new Foo();}
  public Foo withBar(Integer val) {this.bar = val; return this;} 
  public Foo withFie(String val) {this.fie= val; return this;}

  public doWork() {..}
}

and call via

Foo f = Foo.newInstance(); // everything defaults
f.doWork();

or

Foo f = Foo.newInstance()
          .withFie('goofball');  // let bar default
f.doWork();

or

SomeObject t = Foo.newInstance()
          .withBar(10)
          .doWork();  // let fie default and then do the method's work all in one statement

or

Foo f = Foo.newInstance()  // specify all args
          .withBar(10)
          .withFie('smushball');
f.doWork();

the pattern is handy for among other reasons, to self-document the args in the calling code though the pattern has greater use cases in applying repetitive and.or distinct operations to an object in a single statement, typically before transforming the object into something else.

Attribution
Source : Link , Question Author : Andrej Lucansky , Answer Author : cropredy

Leave a Comment