Define APEX method with default arguments

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.


Yes, you have to define method overloads. That is the only way to specify default argument values.