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', '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;


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) { = val; return this;} 
  public Foo withFie(String val) {this.fie= val; return this;}

  public doWork() {..}

and call via

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


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


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


Foo f = Foo.newInstance()  // specify all args

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.

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

Leave a Comment